[英]Syntax to sort more than one column in SQLAlchemy
I am currently using SQLAlchemy
to query
my database as such: 我目前正在使用
SQLAlchemy
这样query
数据库:
returnedOrders = session.query(ORDER).join(RESTAURANT,
and_(ORDER.RESTAURANTSID==RESTAURANT.RESTAURANTSID))\
.filter(ORDER.RESTAURANTSID==restaurantID)\
.order_by(sortOrders(sort_method))\
.all()
def sortOrders(sort_method):
# Date in ascending order
if sort_method == 'date':
return ORDER.ORDERSDATE
# Date in descending order
elif sort_method == '-date':
return desc(ORDER.ORDERSDATE)
# Restaurant then Cost in ascending order
elif sort_method == 'restaurant,cost':
return RESTAURANT.RESTAURANTSNAME, ORDER.ORDERSCOST(???? Error -
SQL expression object or string expected.)
# Restaurant in ascending order then Cost in descending order
elif sort_method == 'restaurant,-cost':
return ???
This seems to be working for the queries
that only involve one column
. 这似乎只对涉及一
column
的queries
。 I'm now trying to figure out how to do this for the last two if
statements but can't seem to get the syntax
right. 我现在正试图找出如何对后两个
if
语句执行此操作,但似乎无法正确使用syntax
。
Is this even possible? 这有可能吗?
Any help with this would be greatly appreciated. 任何帮助,将不胜感激。
It currently does not work because order_by
does not work with tuple
instances. 当前不起作用,因为
order_by
不适用于tuple
实例。 To fix this, you need to expand the arguments to the order_by(...)
. 要解决此问题,您需要将参数扩展到
order_by(...)
。 One way to do it would be to always expand (using * [star]) and always return tuples: 一种方法是始终扩展(使用* [star])并始终返回元组:
returnedOrders = (session
.query(ORDER)
.join(RESTAURANT, and_(ORDER.RESTAURANTSID==RESTAURANT.RESTAURANTSID))
.filter(ORDER.RESTAURANTSID==restaurantID)
.order_by(*sortOrders(sort_method)) # expand tuples
.all()
)
def sortOrders(sort_method):
if sort_method == 'date':
return (ORDER.ORDERSDATE,) # @new: return tuple
elif sort_method == '-date':
return (ORDER.ORDERSDATE.desc(),) # @new: return tuple
elif sort_method == 'restaurant,cost':
return (
RESTAURANT.RESTAURANTSNAME,
ORDER.ORDERSCOST,
)
elif sort_method == 'restaurant,-cost':
return (
RESTAURANT.RESTAURANTSNAME,
ORDER.ORDERSCOST.desc(),
)
else:
assert False, "Unexpected sort method {}".format(sort_method)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.