SQLAlchemy按函数结果排序

时间:2014-12-17 08:58:19

标签: python sql sql-server sqlalchemy

这是我的代码,它正在运行(返回所有难以排序的问题):

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()的代码?我的函数返回一个数字。我试过像:

    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

1 个答案:

答案 0 :(得分:5)

Hybrid attributes是作为Python属性和SQL表达式的特殊方法。只要您的difficulty函数可以用SQL表示,它就可以像普通列一样用于过滤和排序。

例如,如果您根据问题所包含的鹦鹉数计算难度,如果问题超过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())