How can I retrieve the last record in a certain queryset?
You could simply do something like this, using
Also, beware this warning from the Django documentation:
… note that
generally only be called on a QuerySet
which has a defined ordering (e.g.,
when querying against a model which
defines a default ordering, or when
order_by()). If no such ordering
is defined for a given
reverse()on it has no real
effect (the ordering was undefined
prior to calling
reverse(), and will
remain undefined afterward).
latest(field_name=None)returns the latest object in the table, by date, using the field_name provided as the date field.
This example returns the latest Entry in the table, according to the
Django >= 1.6
Added QuerySet methods first() and last() which are convenience methods returning the first or last object matching the filters. Returns None if there are no objects matching.
The simplest way to do it is:
You also use this to get the first entry like so:
To get First object:
To get last objects:
You can use filter
This works for me.
If using django 1.6 and up, its much easier now as the new api been introduced –
It will give latest() with reverse direction.
p.s. – I know its old question, I posting as if going forward someone land on this question, they get to know this new feature and not end up using old method.
When the queryset is already exhausted, you may do this to avoid another db hint –
last = queryset[len(queryset) - 1] if queryset else None
Django doesn’t throw
IndexError in this case.
ProgrammingError(when you run python with -O option)
The simplest way, without having to worry about the current ordering, is to convert the QuerySet to a list so that you can use Python’s normal negative indexing. Like so: