[Django]-In Django, what does latest('date') return when there's more than one possible result?

4👍

According to QuerySet.latest() method source code, it is not the case – latest() does not raise MultipleObjectsReturned, because it limits the result to 1 element:

def latest(self, field_name=None):
    """
    Returns the latest object, according to the model's 'get_latest_by'
    option or optional given field_name.
    """
    latest_by = field_name or self.model._meta.get_latest_by
    assert bool(latest_by), "latest() requires either a field_name parameter or 'get_latest_by' in the model"
    assert self.query.can_filter(), \
        "Cannot change a query once a slice has been taken."
    obj = self._clone()
    obj.query.set_limits(high=1)  # <-- see here
    obj.query.clear_ordering()
    obj.query.add_ordering('-%s' % latest_by)
    return obj.get()

get() however, as visible in its source code, raises MultipleObjectsReturned only if the number of results is different than 1 (when it actually returns this result) and different than 0 (when it raises DoesNotExist).

So although latest() returns result of get(), the get() works on something that has no more than 1 element and you do not need to worry about that corner case. Hopefully it is clear enough.

I believe in this case (when two or more records have the same latest date) Django relies on what is returned from the database.

👤Tadeck

Leave a comment