exAres
exAres

Reputation: 4926

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?

Upvotes: 6

Views: 2847

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121466

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.

Upvotes: 9

Related Questions