Fix Python – SQLAlchemy ORDER BY DESCENDING?

Question

Asked By – AP257

How can I use ORDER BY descending in a 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.

Now we will see solution for issue: SQLAlchemy ORDER BY DESCENDING?


Answer

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

Usage from @jpmc26

This question is answered By – AP257

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0