Retrieving the Last Object

Created on Nov. 13, 2012, 12:44 a.m. by Hevok & updated by Hevok on May 2, 2013, 5:26 p.m.

To retrieve the very last object from a table:

entry = Entry.objects.filter(published=True).order_by('-id')[0]

In raw mysql the optimal synthax would be::

SELECT * FROM table WHERE published=TRUE ORDER BY Z DESC LIMIT 1

This would directly translate into::

entry = Entry.objects.filter(published=True).order_by('-id')[:1][0]

Tags: query, django
Categories: Tutorial
Parent: Web Framework

Update entry (Admin) | See changes

Comment on This Data Unit