Hybrid attributes are special methods that act as both a Python property and a SQL expression. As long as your difficulty
function can be expressed in SQL, it can be used to filter and order like a normal column.
For example, if you calculate difficulty as the number of parrots a problem has, times ten if the problem is older than 30 days, you would use:
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
)
and query it with:
session.query(Problem).order_by(Problem.difficulty.desc())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…