SQLAlchemy按功能顺序排序

SQLAlchemy按功能顺序排序,第1张

SQLAlchemy按功能顺序排序

混合属性是既充当Python属性又充当SQL表达式的特殊方法。只要您的

difficulty
函数可以用SQL表示,它就可以像普通列一样用于过滤和排序。

例如,如果按照问题的鹦鹉数来计算难度,如果问题的天数超过30天,则将其乘以十,则可以使用:

from datetime import datetime, timedeltafrom sqlalchemy import Column, Integer, DateTime, casefrom sqlalchemy.ext.hybrid import hybrid_propertyclass Problem(base):    parrots = Column(Integer, nullable=False, default=1)    created = Column(DateTime, nullable=False, default=datetime.utcnow)    @hybrid_property    def difficulty(self):        # this getter is used when accessing the property of an instance        if self.created <= (datetime.utcnow() - timedelta(30)): return self.parrots * 10        return self.parrots    @difficulty.expression    def difficulty(cls):        # this expression is used when querying the model        return case( [(cls.created <= (datetime.utcnow() - timedelta(30)), cls.parrots * 10)], else_=cls.parrots        )

并查询:

session.query(Problem).order_by(Problem.difficulty.desc())


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4985216.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存