reverse()
Use the reverse()
method to reverse the order in which a queryset’s elements are returned. Calling reverse()
a second time restores the ordering back to the normal direction.
To retrieve the “last” five items in a queryset, you could do this:
my_queryset.reverse()[:5]
Note that this is not quite the same as slicing from the end of a sequence in Python. The above example will return the last item first, then the penultimate item and so on. If we had a Python sequence and looked at seq[-5:]
, we would see the fifth-last item first. Django doesn’t support that mode of access (slicing from the end), because it’s not possible to do it efficiently in SQL.
Also, note that reverse()
should 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 using order_by()
). If no such ordering is defined for a given QuerySet
, calling reverse()
on it has no real effect (the ordering was undefined prior to calling reverse()
, and will remain undefined afterward).
Please login to continue.