Ghi*_*taB 4 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
Run Code Online (Sandbox Code Playgroud)
但我想我必须优化这段代码.是否有可能更改代码order_by和我的功能difficulty()?我的函数返回一个数字.我尝试过类似的东西:
result = DBSession.query(AProblem).filter(
AProblem.parent_id == ACategory.id,
ACategory.parent_id == self.id).order_by(
AProblem.difficulty().desc())
Run Code Online (Sandbox Code Playgroud)
但我收到错误TypeError: 'NoneType' object is not callable.
混合属性是充当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
)
Run Code Online (Sandbox Code Playgroud)
并查询:
session.query(Problem).order_by(Problem.difficulty.desc())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3133 次 |
| 最近记录: |