5

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

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 中的属性排序?(我可以加载所有并在应用程序级别进行排序,但如果有很多记录,那就不好了。其他肮脏的解决方案是提交分数并触发,但顺序和属性似乎更优雅,可能吗?)

4

1 回答 1

10

是的,您需要使用一个称为混合属性的功能。表达式需要用 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)
于 2012-12-30T23:53:37.260 回答