从sqlalchemy关系中选择具有最大值的项目

时间:2015-01-25 19:27:40

标签: python sqlalchemy relationship

鉴于这对课程:

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_propertyrelationship执行此操作,而不是正常property。到目前为止我所拥有的是:

select([ThingInfo])
  .group_by(ThingInfo.thing)
  .having(func.max(ThingInfo.recorded_at))

但是我无法弄清楚如何将其作为单个Thing对象的附件来附加。

1 个答案:

答案 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
  • 我试图找出如何写这个来使用groubby