SQLAlchemy: get the object with the most recent date

How to query a table for an object with the most recent table?

I have a table containing

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 figure out how can I get an object with the last updated field? I am currently 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?

+7
python sqlalchemy
source share
2 answers

You need order by updated and limit to a single result. This should work (I have not tested it, the syntax may be incorrect) -

 Ticker.query.order_by('updated desc').limit(1) 
+8
source share

for version 1.2+:

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

desc

0
source share

All Articles