鉴于这对课程:
class Thing(Base):
id = Column(Integer, primary_key=True)
class ThingInfo(Base):
id = Column(Integer, primary_key=True)
thing_id = Column(Integer, ForeignKey(Thing))
recorded_at = Column(DateTime)
thing = relationship(Thing, backref='all_info')
如何定义要实现的属性Thing.newest_info
:
t = s.query(Thing).first()
newest_info = max(t.all_info, key=lambda i: i.recorded_at)
print newest_info
#equivalent to:
t = s.query(Thing).first()
print t.newest_info
我想使用column_property
或relationship
执行此操作,而不是正常property
。到目前为止我所拥有的是:
select([ThingInfo])
.group_by(ThingInfo.thing)
.having(func.max(ThingInfo.recorded_at))
但是我无法弄清楚如何将其作为单个Thing
对象的附件来附加。
答案 0 :(得分:0)
好的,这是一次尝试:
t = aliased(ThingInfo)
ThingInfo.is_newest = column_property(
select([
ThingInfo.recorded_at == func.max(t.recorded_at)
])
.select_from(r)
.where(t.thing_id == ThingInfo.thing_id)
)
Thing.newest_info = relationship(
ThingInfo,
viewonly=True,
uselist=False,
primaryjoin=(ThingInfo.thing_id == Thing.id) & ThingInfo.is_newest
)
我不喜欢这件事:
Thing
加入ThingInfo