给定这对类:
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
or relationship
,不是正常的property
。到目前为止我所拥有的是:
select([ThingInfo])
.group_by(ThingInfo.thing)
.having(func.max(ThingInfo.recorded_at))
但我不知道如何将其附加为单个属性Thing
object.
Add an order_by
关系的条款,这变得微不足道:
class ThingInfo(Base):
id = Column(Integer, primary_key=True)
thing_id = Column(Integer, ForeignKey(Thing))
recorded_at = Column(DateTime)
thing = relationship(Thing, backref=backref('all_info', order_by='ThingInfo.recorded_at')
thing = session.query(Thing).get(id)
newest_info = thing.all_info[-1]
或者替代地backref=backref('all_info', order_by='desc(ThingInfo.recorded_at)')
and newest_info=thing.all_info[0]
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)