SQLAlchemy ORDER BY DESCENDING?


Question

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.

1
362
10/27/2018 7:00:39 PM

Accepted Answer

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

Usage from @jpmc26

316
7/10/2017 8:56:59 PM

Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:

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

This is handy since you can use it on other places such as in a relation definition, etc.

For more information, you can refer this


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon