从SQLAlchemy的关系选择项目有最大(Select item having maximum f

2019-10-21 16:58发布

鉴于这种对类:

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的对象。

Answer 1:

好吧,这里是一个工作的尝试:

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 s到ThingInfo在第二地S
  • 我试图找出如何写这个使用groubby


文章来源: Select item having maximum from sqlalchemy relationship