I'm new to peewee and can't seem to figure out how to correctly send a query.
Here's my Meta:
class Meta:
database = db
db_table = 'profile'
To my understanding, I told peewee to use the table 'profile'
But when I try to select from the table with:
Profile.get(Profile.name == user)
I always get an error that is referring to the table 't1' and not my table 'profile'
How do I tell peewee to use a specific table and NOT t1?
Peewee uses aliases when constructing queries, so although it's referring to "t1", the query itself will probably look like:
SELECT * FROM "profile" AS "t1" WHERE "t1"."name" = '<whatever>';
Related
I am new to django orm.
I've tables look like this.
class Product(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
name = models.CharField(max_length=60)
class ProductOption(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
product_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)
I would like to query productoption id that related to product. I made query like this to do inner join.
Query = Product.select_related(‘product_id’).filter(name='a')
And it gaves me error message saying
django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'product_id'. Choices are: (none)
I want to know if there is something wrong in models or query.
Use prefetch_related
Product.objects.filter(name='a').prefetch_related('productoption_set')
This is not how you query a related object. Since you used a foreign key and if I understand correctly, you probably want to use something like this:
Product.objects.filter(name='a').productoption_set.all()
I have three tables which is mapped like this: paymentDetails <-employee<-designation.
Now I have to get datas from paymentDetails table by particular designation of employee..
select *
from paymentDetails
where payment_date=date and employee.designation.desig_id=2;
And I am using Yii2 framework How can I achieve this in Yii2.
I get unknown column error. How to resolve this ?
$command = Yii::app()->db->createCommand()
->select(*)
->from('paymentDetails')
->where('payment_date=date')
->andWhere('employee.designation.desig_id=2')
select *
from paymentDetails
where payment_date=date and employee.designation.desig_id=2;
this will not work in SQL either, it is beacause you are using the tables employee and designation and you do not actually join them in any way.
Now you have not given us any details regarding the name of the models, but it should be something like
$paymentDetails = PaymentDetails::find()->joinWith('employee.designation')-where(['employee.designation.desig_id' => 2, 'payment_date' => 'date'])->all();
This will execute
select *
from paymentDetails JOIN employee ON 'theDefinedRelation' JOIN designation ON 'theSecondDefinedRelation' where payment_date=date and employee.designation.desig_id=2;
Anyway, it will be a long day, if you do not know why the SQL fails you have to learn SQL first.
Here is the code from django docs that explains the use of managers.
class PollManager(models.Manager):
def with_counts(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
SELECT p.id, p.question, p.poll_date, COUNT(*)
FROM polls_opinionpoll p, polls_response r
WHERE p.id = r.poll_id
GROUP BY p.id, p.question, p.poll_date
ORDER BY p.poll_date DESC""")
result_list = []
for row in cursor.fetchall():
p = self.model(id=row[0], question=row[1], poll_date=row[2])
p.num_responses = row[3]
result_list.append(p)
return result_list
class OpinionPoll(models.Model):
question = models.CharField(max_length=200)
poll_date = models.DateField()
objects = PollManager()
class Response(models.Model):
poll = models.ForeignKey(OpinionPoll)
person_name = models.CharField(max_length=50)
response = models.TextField()
I have two questions based on this code:
1) where is r.poll_id coming from? I understand Response has foreignKey relationship to OpinionPoll. In order to JOIN OpinionPoll table with Response table, I need to join on their id.
HOwever to access the poll id in Response, I would do r.poll.id.
Is the syntax, r.poll_id, a MySQL syntax.
why GROUP BY p.id, p.question, p.poll_date? why GROUP BY p.id alone is not sufficient?
2) Is it possible to turn the above raw SQL query into a django ORM query?If so how would that look like?
I am not a SQL guy. so bear with me, if this sounds stupid
EDIT:
If I want to create OpinionPoll and Response tables outside of Django, how will SQL statment for create look like?
In the Django shell, when I run
python manage.py sqlall appname
I get the following:
BEGIN;
CREATE TABLE "myapp_opinionpoll" (
"id" integer NOT NULL PRIMARY KEY,
"question" varchar(200) NOT NULL,
"poll_date" date NOT NULL
)
;
CREATE TABLE "myapp_response" (
"id" integer NOT NULL PRIMARY KEY,
"poll_id" integer NOT NULL REFERENCES "myapp_opinionpoll" ("id"),
"person_name" varchar(50) NOT NULL,
"response" text NOT NULL
)
;
CREATE INDEX "larb_response_70f78e6b" ON "myapp_response" ("poll_id");
COMMIT;
I see something like REFERENCES "myapp_opinionpoll" and CREATE INDEXabove. I am not sure
if this is how in SQL it is done?
[1] Django model will create foreign keys like fieldname_id as the field in mysql. So you see the field poll = models.ForeignKey(OpinionPoll) creates this field.
About GROUP BY, because these fields are exactly what selected, except for the aggregate function, grouping them exactly can make them distinct.
[2] Try this, I didn't debug, but may helps:
from django.db.models import Count
OpinionPoll.objects.annotate(num_responses=Count('response'))
For more about aggregation, see the docs: https://docs.djangoproject.com/en/1.6/topics/db/aggregation/
Hi i am writing an spring mvc, employee application using mysql database,hibernate annotations and jsp . The database contains one table "Empdata" where empid is primary key.And there is a column "team" in "Empdata".I want to select employees in a specific team, example all the details of employees in "Team1".Here i can perform delete and edit operations in the application. For delete operation i am using
sessionfactory.getCurrentSession().createQuery("DELETE FROM Resource WHERE empid=" +resource.getEmpId()).executeUpdate();
query.I know the command line query for select is
SELECT * FROM EmpData WHERE EMPLTEAM ="Team1"
I want to know how to convert this query into hibernate?
please help,thanks in advance..
Query query = session.createQuery("from Resource where emplteam = :team");
query.setParameter("team", "Team1");
List list = query.list();
emplteam should be the property of your class Resource , not your database column's name.
I guess it is simple using HQL .
String hql = "FROM Resource E WHERE E.emplteam = team1";
Query query = session.createQuery(hql);
List results = query.list();
Hope this helps
Note: Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.
have you tried using criteria api?
Criteria crit = sessionFactory.getCurrentSession()
.createCriteria(EmpData.class).add(Restrictions.eq("EMPLTEAM", "teamxxx");
List<EmpData> result = crit.list();
For example
Query query = session.createQuery("from Student where name=:name");
query.setParameter("name", "Raj");
In your case i guess the Entity name is Empdata(The object that represent the table)
And the field in the object is team(That has getter and setter in object)
Query query = session.createQuery("from Empdata where team=:teamParam");
query.setParameter("teamParam", "team1");
I have this method
class User < ActiveRecord::Base
def self.search(q, with_address)
klass = self
klass = klass.includes(:address) if with_address
klass.where("users.name LIKE ?", "%#{q}%")
end
end
I need to add the users.name in the query so that it knows to which table it refers. But when :address is not included, I have a message:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "users.name" does not exist
How can I enforce the table name prefix in the query? Something like AS users in SQL.
Using Rails 3.2
Thanks