Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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)

.join(model.EnumerationValue)

.filter_by(id=c.row.id)
.order_by(model.Entry.amount) # This row :)

)

If I try:

.order_by(desc(model.Entry.amount))

then I get:

NameError: global name 'desc' is not defined.

2 Answers

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:-

.order_by(model.Entry.amount.desc())

0 votes
by (1.5k points)

To implement ORDER BY DESCENDING in SQLAlchemy, we can use order_by() method with the desc() function.

Ensure that you have imported desc() function from SQLAlchemy

Here’s a query example that you can use

from sqlalchemy import desc

# Query with ORDER BY descending

users = session.query(User).order_by(desc(User.age)).all()

This line sorts the query results descending based on the age column in the User model.

Related questions

0 votes
3 answers
asked Mar 22, 2021 in Python by Rekha (2.2k points)
0 votes
1 answer
asked Sep 17, 2019 in Python by Sammy (47.6k points)

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...