PageView

Subscribe to our YouTube Channel!
[Jul 12, 2021] New Video: How to Use Django Rest Framework Permissions (DRF Tutorial - Part 7)


Django Tips #17 Using QuerySet Latest & Earliest Methods

Django Tips #17 Using QuerySet Latest & Earliest Methods

Similar to the QuerySet methods first and last, the API also offer the earliest and latest methods. They are convenience methods which can be used to enhance the readability of the code.

The best way to use it is to define get_latest_by in the model’s Meta class:

class Post(models.Model):
    headline = models.CharField(max_length=150)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    publication_date = models.DateTimeField(blank=True, null=True)
    change_date = models.DateTimeField(blank=True, null=True)

    class Meta:
        get_latest_by = 'publication_date'

Then the usage is very straightforward:

latest_post = Post.objects.latest()
earliest_post = Post.objects.earliest()

If you didn’t specify the get_latest_by property, or if you want to use a different field, you can pass it as a parameter on the fly:

latest_change = Post.objects.latest('change_date')

The earliest and latest methods will raise a DoesNotExist exception if there is no object with the given parameters, that is, the table is empty or it was filtered. It is slightly different from first and last, because it returns None if there is no matching object.

Another important thing to note is that the earliest and latest methods might return instances with null dates. But the thing is, the ordering behavior is not consistent between the different databases. So you might want to remove null dates, like so:

Post.objects.filter(change_date__isnull=False).latest('change_date')

Typically it is used with either DateField, DateTimeField or IntegerField. It will work with other field types. But you should avoid it, because it will be semantically wrong, and as those methods are available just for convinience and to enhance readability, in that case, using for something different than dates will cause more confusion.