SQLAlchemy按函数排序resu

2024-10-01 09:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码,它正在工作(返回按难度排序的所有问题):

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

^{pr2}$

但是我收到错误TypeError: 'NoneType' object is not callable。在


Tags: 函数代码selfid排序defallparent
1条回答
网友
1楼 · 发布于 2024-10-01 09:23:44

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

例如,如果将难度计算为问题的鹦鹉数量,乘以10(如果问题超过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
        )

并查询:

^{pr2}$

相关问题 更多 >