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
.
all() will return all records which match our query as a list of objects.
A scalar subquery is a subquery that selects only one column or expression and returns one row. A scalar subquery can be used anywhere in an SQL query that a column or expression can be used.
The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.
first() , which will give you just the first result of possibly many, without raising those exceptions.
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 it avoids an import
, and you can use it on other places such as in a relation definition, etc.
For more information, you can refer this SQLAlchemy 1.4 Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With