我有两个这样的 ORM 类:
class Road(Base):
__tablename__ = "road"
id = Column(Integer, primary_key=True)
@hybrid_method
def total_traffic(self, days):
today_date = datetime.datetime.now().date()
future_date = today_date+datetime.timedelta(days)
return sum([traffic.volume
for traffic in self.traffic
if traffic.date >= today_date and traffic.date < future_date])
@total_traffic.expression
def total_traffic(cls, days):
today_date = datetime.datetime.now().date()
future_date = today_date+datetime.timedelta(days)
return select([func.sum(RoadTraffic.volume)]).\
where(RoadTraffic.road_id == cls.id).\
where(RoadTraffic.date >= today_date).\
where(RoadTraffic.date < future_date).\
label("total_traffic")
class RoadTraffic(Base):
__tablename__ = "road_traffic"
id = Column(Integer, primary_key=True)
volume = Column(Integer)
date = Column(Date, nullable=False)
road_id = Column(Integer, ForeignKey('road.id'), nullable=False)
road = relationship("Road", backref=backref('traffic'))
这在功能上非常棒,但在完整的数据集上获取所有流量数据并在本地汇总它有点慢(生产中为 4 秒),即使有连接负载。我可以像这样选择道路旁边的 total_traffic:
roads_with_traffic = db.query(Orn, Orn.total_traffic(7)).all()
但后来我必须改变我的观点来接收这个而不是纯粹的道路清单。
在相关对象上缓存选定的 total_traffic 是否有约定?