Denigma
hevok @hevok November 13, 2012
Tutorial #django #query

Retrieving the Last Object

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](/blog/651/) * 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]