Table of Content
- How to Use the Latest & Earliest Methods in Django QuerySet
- Additional Information on earliest and latest methods
- Wrap Off
Django API offers two methods earliest
and latest
methods, which are similar to the QuerySet methods first
and last
.
They are convenience methods that can be used to enhance the readability of the code.
There are two ways to use it:
-
Using the model's Meta class
The best way to uselatest
methods is to defineget_latest_by
in the model's Meta class:class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) published = models.DateTimeField(blank=True, null=True) updated = models.DateTimeField(blank=True, null=True) class Meta: get_latest_by = 'published'
Highlighted code sample. Here's how you will use it:
latest_book = Book.objects.latest() earliest_book = Book.objects.earliest()
Highlighted code sample. -
Using it when accessing the objects
You can pass the latest or earliest methods as a parameter on the fly when calling the query set:
last_updated = Book.objects.latest('updated')
Highlighted code sample.
Additional Information on earliest
and latest
methods
The earliest
and latest
methods will raise a DoesNotExist
exception if there is no object with the given parameters, that is, if the table is empty, or the filtered criteria returned no result.
It is slightly different from first
and last
, because they return None
if there is no matching object.
You should also know 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:
Book.objects.filter(updated__isnull=False).latest('updated')
Typically, it is used with either DateField
, DateTimeField
or IntegerField
.
It will also work with other field types.
But you should avoid it because it will be semantically wrong since the earliest
and latest
methods are available for convenience and to enhance readability.
This means that using them for something different from dates will cause more confusion.
Wrap Off
I hope you found this post useful somehow!
If you have any questions or need clarification, feel free to reach out to me.
If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.