现在我正在做的是:
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()
有没有办法只调用一次order_by
,并使用order_type
中提供的排序顺序作为变量来决定是否对asc
或desc
?
最佳答案
direction = desc if order_type == 'desc' else asc
result = session.\
query(Customer).\
order_by(direction(getattr(Customer, sorting_column_name))).\
all()
direction
根据 order_type
的值绑定(bind)到 asc
或 desc
,然后用于构建查询。
关于python - 如何在 sqlalchemy 中的变量中提供排序顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24992485/