Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy ORDER BY DESCENDING?

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.

like image 883
AP257 Avatar asked Nov 15 '10 15:11

AP257


People also ask

What does query all () return?

all() will return all records which match our query as a list of objects.

What is scalar subquery SQLAlchemy?

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.

What is subquery in SQLAlchemy?

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.

What is first in SQLAlchemy?

first() , which will give you just the first result of possibly many, without raising those exceptions.


1 Answers

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

like image 92
Rick Avatar answered Sep 28 '22 03:09

Rick