[Django]-Why does using .latest() on an empty Django queryset return…nothing?

6👍

From the documentation:

Like get(), earliest() and latest() raise DoesNotExist if there is no object with the given parameters.

qs.latest('field') should raise Model.DoesNotExist exception whenever qs is an empty queryset.

In [2]: Entity.objects.none().latest('creation_date')
---------------------------------------------------------------------------
DoesNotExist                              Traceback (most recent call last)

Check the exception is not swallowed in your view/method.

9👍

If you would like it to return None instead of throw an error, you could use order_by() and last().

qs.order_by('time_completed').last()

This will return None if the queryset is empty.

👤mhatch

Leave a comment