What is the difference between queryset last() and latest() in django?

Viewed 65

I want to get data which inserted in the last so I used a django code

user = CustomUser.objects.filter(email=email).last()

So it gives me the last user detail.

But then experimentally I used:

user = CustomUser.objects.filter(email=email).latest()

Then It didn't give me a user object. Now, what is the difference between earliest(), latest, first and last()?

1 Answers

There are several differences between .first() [Django-doc]/.last() [Django-doc] and .earliest(…) [Django-doc]/.latest(…) [Django-doc]. The main ones are:

  • .first() and .last() do not take field names (or orderable expressions) to order by, they do not have parameters, .earliest(…) and .latest(…) do;
  • .first() and .last() will work with the ordering of the queryset if there is one, .earliest(…) and .latest(…) will omit any .order_by(…) clause that has already been used;
  • if the queryset is not ordered .first() and .last() will order by the primary key and return the first/last item of that queryset, .earliest(…) and .latest(…) will look for the get_latest_by model option [Django-doc] if no fields are specified; and
  • .first() and .last() will return None in case the queryset is empty; whereas .earliest(…) and .latest(…) will raise a DoesNotExist exception [Django-doc].
Related