gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:44:39 25 4
gpt4 key购买 nike

给定这对类:

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

最佳答案

添加 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)')newest_info=thing.all_info[0] .

关于python - 从 sqlalchemy 关系中选择具有最大值的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28140520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com