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
.
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
from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))
Usage from @jpmc26
One other thing you might do is:
.order_by("name desc")
This will result in: ORDER BY name desc. The disadvantage here is the explicit column name used in order by.
You can use .desc()
function in your query just like this
query = (model.Session.query(model.Entry)
.join(model.ClassificationItem)
.join(model.EnumerationValue)
.filter_by(id=c.row.id)
.order_by(model.Entry.amount.desc())
)
This will order by amount in descending order
or
query = session.query(
model.Entry
).join(
model.ClassificationItem
).join(
model.EnumerationValue
).filter_by(
id=c.row.id
).order_by(
model.Entry.amount.desc()
)
)
Complementary at @Radu answer, As in SQL, you can add the table name in the parameter if you have many table with the same attribute.
.order_by("TableName.name desc")
We can do it in multiple ways.The simplest one will be to do it in the following way-
res=ModelName.query.filter(ModelName.var1==cond).order_by(ModelName.var1.desc())