可以通过使用模型中的属性来订购吗?

时间:2012-12-28 18:43:54

标签: sqlalchemy

可以通过使用模型中的属性进行排序吗?

class PlayerModel(Base):
    __tablename__ = 'players'
    alliances_id = Column(Integer, ForeignKey('alliances.id'), nullable=True)
    alliance = relationship('AllianceModel')
    username = Column(String(30), nullable=False)
    wins = Column(Integer, default=0, nullable=False)
    defeats = Column(Integer, default=0, nullable=False)

    @property
    def score(self):
        number = self.wins + self.defeats
        if number:
            return self.wins / number
        return 0
查询中的

 `for player in session.query(PlayerModel).order_by(PlayerModel.wins+PlayerModel.defeats):`

它有效,但是当我放

时,id不起作用
session.query(PlayerModel).order_by(PlayerModel.wins+PlayerModel.score):`

它报告错误期望SQL字符串。可以在desc中按属性排序吗? (我可以加载所有并在应用程序级别排序但是如果有很多记录则很糟糕。其他脏的解决方案是得分和触发,但是顺序和属性看起来更优雅,是否可能?)

1 个答案:

答案 0 :(得分:8)

是的,您需要使用名为hybrid attributes的功能。表达式需要根据Python逻辑和SQL表达式逻辑来陈述:

from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import case

class PlayerModel(Base):
    __tablename__ = 'players'
    alliances_id = Column(Integer, ForeignKey('alliances.id'), nullable=True)
    alliance = relationship('AllianceModel')
    username = Column(String(30), nullable=False)
    wins = Column(Integer, default=0, nullable=False)
    defeats = Column(Integer, default=0, nullable=False)

    @hybrid_property
    def score(self):
        number = self.wins + self.defeats
        if number:
            return self.wins / number
        return 0

    @score.expression
    def score(cls):
        number = cls.wins + cls.defeats
        return case([(number > 0, cls.wins / number)], else_ = 0)