Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 963
Lucas Kauffman Avatar asked Jan 05 '14 19:01

Lucas Kauffman


2 Answers

for version 1.2+:

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

desc

like image 156
MCH Avatar answered Oct 02 '22 13:10

MCH


You need to order by updated and limit to one result. This should work(I haven't tested it, syntax might be wrong) -

Ticker.query.order_by('updated desc').limit(1)
like image 24
Bibhas Debnath Avatar answered Oct 02 '22 13:10

Bibhas Debnath