Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last Record in Column, SQLALCHEMY

I tried to get last record in my column using this

 ObjectRes.query.order_by('-id').first()

But the result is : None

I tried using all other queries, The only thing that works is

obj = ObjectRes.query.all()
return str(obj[-1].id)

The query is too heavy, Need lighter queries that work with this on Pythonanywhere. Thanks

like image 538
Salman Farsi Avatar asked Apr 02 '18 07:04

Salman Farsi


Video Answer


1 Answers

Columns in SQLAlchemy models have methods attached to produce this behaviour. To order by ID descending, do this:

descending = Object.query.order_by(Object.id.desc())
last_item = descending.first()

Specifying Object.field is the clearest syntax for choosing a field to order by, and all columns / model attributes should support .desc() or .asc()

You can of course do this in a one liner as well:

last_item = Object.query.order_by(Object.id.desc()).first()
like image 67
daveruinseverything Avatar answered Oct 06 '22 00:10

daveruinseverything