How to Use first() and last() in Django QuerySets
In Django, you can use
first() and last() methods on QuerySets to retrieve the first or last record respectively. These methods return a single model instance or None if no records exist.Syntax
The first() and last() methods are called on a Django QuerySet to get the first or last object in the result set.
queryset.first(): Returns the first object orNoneif empty.queryset.last(): Returns the last object orNoneif empty.
python
first_object = MyModel.objects.filter(active=True).order_by('created_at').first() last_object = MyModel.objects.filter(active=True).order_by('created_at').last()
Example
This example shows how to get the first and last user ordered by their signup date.
python
from django.contrib.auth.models import User # Get the first user by date joined first_user = User.objects.order_by('date_joined').first() # Get the last user by date joined last_user = User.objects.order_by('date_joined').last() print(f"First user: {first_user.username if first_user else 'None'}") print(f"Last user: {last_user.username if last_user else 'None'}")
Output
First user: alice
Last user: zoe
Common Pitfalls
Common mistakes include:
- Not ordering the QuerySet before calling
first()orlast(), which can lead to unpredictable results. - Assuming these methods raise exceptions if no records exist; they return
Noneinstead. - Using
first()orlast()on unsorted QuerySets when order matters.
python
wrong = MyModel.objects.first() # No order, unpredictable first record right = MyModel.objects.order_by('id').first() # Ordered, predictable first record
Quick Reference
| Method | Description | Returns if empty |
|---|---|---|
| first() | Returns first object in QuerySet | None |
| last() | Returns last object in QuerySet | None |
Key Takeaways
Always use order_by() before first() or last() to get predictable results.
first() and last() return a single object or None if no records exist.
They do not raise exceptions on empty QuerySets.
Use these methods to quickly access boundary records without slicing.
They work on any QuerySet, including filtered and ordered ones.