简体   繁体   English

SQLAlchemy:获取具有最新日期的对象

[英]SQLAlchemy: get the object with the most recent date

How do I query a table for the object with the most recent table?如何在表中查询具有最新表的对象?

I've got a table which holds我有一张桌子

class Ticker(Base):
    updated = Column('updated', DATETIME, index=False, nullable=False,primary_key=True)
    high = Column('high', FLOAT, index=False, nullable=False)

I'm trying to find out how I can get the object with the most recent updated field?我正在尝试找出如何获取具有最新更新字段的对象? Currently I'm doing the following:目前我正在做以下事情:

maxdate = db_session.query(func.max(Ticker.updated)).first()[0]
Ticker.query.filter(Ticker.updated == maxdate).first()

I was wondering if there is a more efficient/shorter way to do this?我想知道是否有更有效/更短的方法来做到这一点?

You need to order by updated and limit to one result. 您需要通过 updated 订购限制为一个结果。 This should work(I haven't tested it, syntax might be wrong) - 这应该工作(我没有测试过,语法可能是错误的) -

Ticker.query.order_by('updated desc').limit(1)

for version 1.2+: 对于版本1.2+:

session.query(Ticker).order_by(desc('updated')).first()

desc 降序

Same as this with a small variation in syntax:相同,语法略有不同:

session.query(Ticker).order_by(Ticker.updated.desc()).limit(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM