简体   繁体   English

Sqlalchemy按计算列排序

[英]Sqlalchemy order by calculated column

I'm trying to build a select query using sqlalchemy, but I need to sort the results by a calculated value and I'm not sure how to do it. 我正在尝试使用sqlalchemy构建一个选择查询,但我需要按计算值对结果进行排序,我不知道该怎么做。

Basically, I have a 'start_time' and 'end_time' columns and I want to order the results based on start_time and then end_time but if end_time < start_time I want to add 86400000 to it: 基本上,我有一个'start_time'和'end_time'列,我想根据start_time和end_time来排序结果,但是如果end_time <start_time我想要添加86400000:

end_time + (86400000 if end_time < start_time else 0)

I can't figure out how to do it. 我无法弄清楚该怎么做。 Is there any simple way to add a calculated property to my table class and have the query retrieve that property? 有没有简单的方法将计算属性添加到我的表类并让查询检索该属性?

I've tried using @property to create a getter for that calculated end_time but it didn't work. 我已经尝试使用@property为计算出的end_time创建一个getter,但它没有用。

First you need to define column that will contain your formula implemented as sql function(s) 首先,您需要定义将包含实现为sql函数的公式的列

Than you build your query using defined column: 比使用定义的列构建查询:

col = tclass.end_time + case([(tclass.end_time<tclass.start_time, 86400000)], else_=0 )
q = session.query(col).order_by(col)
print q

There is also way to add such calculated column to the Mapped Object class defintion: 还有一种方法可以将这样计算的列添加到Mapped Object类定义中:

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)

The sqlalchemy documentation now seems to recommend using a hybrid to do this. sqlalchemy文档现在似乎建议使用混合来执行此操作。

Example: 例:

from sqlalchemy.ext.hybrid import hybrid_property

class Tname(Base):
    end_time = Column(Integer)
    start_time = Column(Integer)

    @hybrid_property
    def calc_column(self):
        if self.end_time < self.start_time:
            return self.end_time + 86400000 
        else: 
            return self.end_time

Then you can just run a typical query and order by calc_column. 然后,您可以通过calc_column运行典型的查询和订单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM