SQLAlchemy按计算列排序
问题内容:
我正在尝试使用sqlalchemy建立选择查询,但是我需要按计算值对结果进行排序,但我不确定该怎么做。
基本上,我有一个“ start_time”和“ end_time”列,我想根据start_time然后end_time排序结果,但是如果end_time
<start_time,我想添加86400000:
end_time + (86400000 if end_time < start_time else 0)
我不知道该怎么做。有什么简单的方法可以将计算出的属性添加到我的表类中,并让查询检索该属性?
我尝试使用@property为该计算出的end_time创建一个吸气剂,但是没有用。
问题答案:
首先,您需要定义一列,其中将包含实现为sql函数的公式
比您使用定义的列构建查询:
col = tclass.end_time + case([(tclass.end_time<tclass.start_time, 86400000)], else_=0 )
q = session.query(col).order_by(col)
print q
还有一种方法可以将这样的计算列添加到“映射对象”类定义中:
class TName(Base):
end_time = Column(Integer)
start_time = Column(Integer)
calc_column = end_time + case([(end_time<start_time, 86400000)], else_=0 )
q2 = session.query(TName.calc_column).order_by(TName.calc_column)