Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

How can I use ORDER BY descending in an SQLAlchemy query like the following?

This query works, but returns them in ascending order:

query = (model.Session.query(model.Entry) .join(model.ClassificationItem)


.order_by(model.Entry.amount) # This row :)


If I try:


then I get:

NameError: global name 'desc' is not defined.

1 Answer

0 votes
by (106k points)

There are many ways of using ORDER BY descending in an SQLAlchemy but some of the important ways I am discussing here:-

You can import desc from the sqlalchemy package and use the function someselect.order_by() function it will do the task.

from sqlalchemy import desc someselect.order_by(desc(table1.mycol))

Another way you can do is to specify those things as column attributes. Like I am mentioning below. This way becomes handy when you see the relation definition type of things:-


Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
asked Jul 22, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories