select *
from article_article
left join article_upvote ON article_article.id=article_upvote.article_id
I want to write this query with Django ORM. How can I write this? Please help
You can use prefetch related:
articles = Article.objects.all().prefetch_related('upvote')
If you want to see the query executed do:
print(articles.query)
Related
I want to display the course name along with the question count in a table. Need help to convert below query to a django ORM:
SELECT DISTINCT exam_course.course_name,
COUNT(exam_question.question)
FROM exam_course
INNER JOIN exam_question ON exam_question.course_id = exam_course.id
GROUP BY exam_question.course_id
Use annotate with count as commented...use in this manner, replace accordingly your requirements:
invoices = Invoice.objects.annotate(total_amount=Sum('order__order_items__amount'),number_of_invoices=Count('pk', distinct=True))
I have the following issue, i need to convert the following query into python's sqlalchemy orm:
SELECT parts.model_num,
ptemp_objects.ptemp_id, ptemp_objects.type, ptemp_objects.area, ptemp_objects.text, ptemp_objects.x, ptemp_objects.y, ptemp_objects.width, ptemp_objects.height, ptemp_objects.font, ptemp_objects.font_size, ptemp_objects.alignment, ptemp_objects.bold, ptemp_objects.italic, ptemp_objects.display_order,
ptype_areas.x, ptype_areas.y, ptype_areas.name, ptype_areas.width, ptype_areas.height,
paper_types.name, paper_types.width, paper_types.height, paper_types.left_margin, paper_types.right_margin, paper_types.top_margin, paper_types.bottom_margin,
print_images.path
FROM parts
JOIN prints
ON prints.part_id = parts.id
JOIN ptemp_objects
ON prints.ptemp_id = ptemp_objects.ptemp_id
JOIN ptype_areas
ON ptemp_objects.area = ptype_areas.id
JOIN paper_types
ON ptype_areas.ptype_id = paper_types.id
LEFT JOIN print_images
ON ptemp_objects.type = print_images.id
where prints.part_id = 879 and parts.model_num="BD854-20-YN-125-BN";
I have been trying with this:
session.query(Table1, Table2, Table3).select_from(Table1).join(Table2).join(Table3).all()
but i dont know how to build this in python's sqlalchemy nor how to declare it with so many foreign keys.
I am a beginner using this orm, i've been reading sqlalchemy's documentation but i have not been able to understand it well nor i have not found any solution to build this query. It would be great if you could help me to build this and a bit of explain also would be good.
Thanks!
I am using:
Windows 10 Professional.
Python 3.8.8.
Visual Studio Code.
SQLAlchemy 1.4.22
I could figure out the way to perform many joins into python's sqlalchemy,
basically i performed this code in python:
query = session.query(Parts.model_num, Parts.description, PtempObjects.text,PtypeAreas, PrintImages).select_from(Parts)\
.join(Prints,Prints.part_id==Parts.id)\
.join(PtempObjects,Prints.ptemp_id==PtempObjects.ptemp_id)\
.join(PtypeAreas,PtypeAreas.id==PtempObjects.area)\
.join(PrintImages,PrintImages.id==PtempObjects.type, isouter=True)\
.filter(Prints.part_id==879,Parts.model_num=="BD854-20-YN-125-BN")
I am starting to use sqlalchemy in an ORM way rather than in an SQL way. I have been through the doc quickly but I don't find how to easily do the equivalent of SQL:
select max(Table1.Date) from Table1, Table2
where...
I can do:
session.query(Table1, Table2)
...
order_by(Table1.c.Date.desc())
and then select the first row but it must be quite inefficient. Could anyone tell me what is the proper way to select the max?
Many thanks
Ideally one would know the other parts of the query. But without any additional information, below should do it
import sqlalchemy as sa
q = (
session
.query(sa.func.max(Table1.date))
.select_from(Table1, Table2) # or any other `.join(Table2)` would do
.filter(...)
.order_by(Table1.c.Date.desc())
)
We are testing the possibility to implement SQLAlchemy to handle our database work. In some instances I need to join a database to a clone of itself (with potentially different data, of course).
An example of the SQL I need to replicate is as follows:
SELECT lt.name, lt.date, lt.type
FROM dbA.dbo.TableName as lt
LEFT JOIN dbB.dbo.TableName as rt
ON lt.name = rt.name
AND lt.date = rt.date
WHERE rt.type is NULL
So far I have tried using the join object but I can't get it to not spit the entire join out. I have also tried various .join() methods based on the tutorial here: http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html and I keep getting an AttributeError: "mapper" or not what I'm looking for.
The issues I'm running into is that I need to not only join on multiple fields, but I can't have any foreign key relationships built into the objects or tables.
Thanks to Kay's like I think I figured out the solution.
It looks like it can be solved by:
session.query(dbA_TableName).outerjoin(
dbB_TableName,
and_(dbA_TableName.name == dbB_TableName.name",
dbA_TableName.date == dbB_TableName.date")
).filter("dbB_TableName.type is NULL")`
The following query I'd love to do in django, ideally without using iteration. I just want the database call to return the result denoted by the query below. Unfortunately according to the docs this doesn't seem to be possible; only the general functions like Avg, Max and Min etc are available. Currently I'm using django 1.4 but I'm happy to rewrite stuff from django 1.8 (hence the docs page; I've heard that 1.8 does a lot of these things much better than 1.4)
select sum(c.attr1 * fs.attr2)/ sum(c.attr1) from fancyStatistics as fs
left join superData s on fs.super_id=s.id
left join crazyData c on s.crazy_id=c.id;
Note:
The main reason for doing this in django directly is that if we ever want to change our database from MySQL to something more appropriate for django, it would be good not to have to rewrite all the queries.
You should be able to get aggregates with F expressions to do most of what you want without dropping into SQL.
https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#joins-and-aggregates
aggregate_dict = FancyStatistics.objects.all()\
.aggregate(
sum1=Sum(
F('superdata__crazydata__attr1') * F('attr2'), output_field=FloatField()
) ,
sum2=Sum('superdata__crazydata__attr1')
)
)
result = aggregate_dict['sum1'] / aggregate_dict['sum2']
You need to specify the output fields if the data types used are different.
You can do that query in Django directly using your SQL expression. Check the docs concerning performing raw SQL queries.