问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/24992485/how-to-provide-the-sort-order-in-a-variable-in-sqlalchemy