Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide the sort order in a variable in sqlalchemy?

Right now what I am doing is as :

if order_type == 'desc':
    result = session.\
             query(Customer).\
             order_by(desc(getattr(Customer, sorting_column_name))).\
             all()
else:
    result = session.\
             query(Customer).\
             order_by(asc(getattr(Customer, sorting_column_name))).\
             all()

Is there any way to call order_by just once and use sorting order provided in order_type as a variable to decide whether to sort asc or desc?

like image 967
exAres Avatar asked Jul 28 '14 09:07

exAres


People also ask

What is first () in SQLAlchemy?

filter() - filter on SQL expressions. method sqlalchemy.orm.Query. first() Return the first result of this Query or None if the result doesn't contain any row.

What is difference between filter and filter by in SQLAlchemy?

The second one, filter_by(), may be used only for filtering by something specifically stated - a string or some number value. So it's usable only for category filtering, not for expression filtering. On the other hand filter() allows using comparison expressions (==, <, >, etc.)

What is C in SQLAlchemy?

c collection is extracted to form a collection of ColumnElement objects. This parameter will also accept TextClause constructs as given, as well as ORM-mapped classes. function sqlalchemy.sql.expression. table(name, *columns, **kw)

What is label in SQLAlchemy?

Label is a class within the sqlalchemy. sql. elements module of the SQLAlchemy project.


Video Answer


1 Answers

asc and desc are just objects, pick one based on the ordering you want:

direction = desc if order_type == 'desc' else asc

result = session.\
         query(Customer).\
         order_by(direction(getattr(Customer, sorting_column_name))).\
         all()

direction is bound to either asc or desc depending on the value of order_type, then used in building the query.

like image 200
Martijn Pieters Avatar answered Nov 14 '22 21:11

Martijn Pieters