Salman Farsi
Salman Farsi

Reputation: 466

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

Upvotes: 7

Views: 10648

Answers (2)

Evan ApRhys
Evan ApRhys

Reputation: 1

I'd comment, but I need 50 rep, so, sorry deveruinseverything, im going to ruin your answer and say it's incomplete (joke). Although, it could be Sqlalchemy has changed in the last 4 years, and not your fault at all.

You need to add (Object) between .query and .order_by

two line answer should look like:

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

One line answer should look like:

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

Upvotes: -2

daveruinseverything
daveruinseverything

Reputation: 5167

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()

Upvotes: 14

Related Questions