gpt4 book ai didi

python - SQLAlchemy 按函数结果排序

转载 作者:太空狗 更新时间:2023-10-30 02:44:51 25 4
gpt4 key购买 nike

这是我的代码并且可以正常工作(返回按难度排序的所有问题):

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

最佳答案

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

例如,如果您将难度计算为一个问题的鹦鹉数量,如果问题超过 30 天,则乘以 10,您将使用:

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())

关于python - SQLAlchemy 按函数结果排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27521645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com