这是我拥有的代码,并且可以正常工作(返回按难度排序的所有问题):
def get_noteworthy_problems(self): ACategory = aliased(Category) AProblem = aliased(Problem) all_prob = DBSession.query(AProblem).filter( AProblem.parent_id == ACategory.id, ACategory.parent_id == self.id) noteworthy_problems = \ sorted(all_prob, key=lambda x: x.difficulty(), reverse=True) return noteworthy_problems
但是我认为我必须优化此代码。有可能更改具有order_by我的功能的代码difficulty()吗?我的函数返回一个数字。我尝试了类似的东西:
order_by
difficulty()
result = DBSession.query(AProblem).filter( AProblem.parent_id == ACategory.id, ACategory.parent_id == self.id).order_by( AProblem.difficulty().desc())
但我收到错误消息TypeError: 'NoneType' object is not callable。
TypeError: 'NoneType' object is not callable
混合属性是既充当Python属性又充当SQL表达式的特殊方法。只要您的difficulty函数可以用SQL表示,它就可以像普通列一样用于过滤和排序。
difficulty
例如,如果按照问题的鹦鹉数来计算难度,如果问题的天数超过30天,则将其乘以十,则可以使用:
from datetime import datetime, timedelta from sqlalchemy import Column, Integer, DateTime, case from sqlalchemy.ext.hybrid import hybrid_property class 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())