Reputation: 466
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
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
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