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

纵饮孤独 提交于 2019-12-31 02:00:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!