0
0
DjangoHow-ToBeginner · 3 min read

How to Filter Objects in Django: Syntax and Examples

In Django, you filter objects using the filter() method on a model's QuerySet, passing keyword arguments that specify conditions. This returns a new QuerySet with objects matching those conditions.
📐

Syntax

The basic syntax to filter objects in Django is using the filter() method on a model's manager or QuerySet. You provide conditions as keyword arguments where the key is the field name and the value is the filter value.

  • Model.objects.filter(field=value): Returns objects where field equals value.
  • You can chain multiple conditions: filter(field1=value1, field2=value2).
  • Use double underscores __ for lookups like field__lookup=value (e.g., age__gte=18 for age greater or equal to 18).
python
Model.objects.filter(field=value)
Model.objects.filter(field1=value1, field2=value2)
Model.objects.filter(field__lookup=value)
💻

Example

This example shows how to filter a list of Book objects to find those published after 2010 and with more than 300 pages.

python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    published_year = models.IntegerField()
    pages = models.IntegerField()

# Filtering books published after 2010 with more than 300 pages
books = Book.objects.filter(published_year__gt=2010, pages__gt=300)

for book in books:
    print(f"{book.title} ({book.published_year}) - {book.pages} pages")
Output
Clean Code (2012) - 450 pages Deep Learning (2016) - 400 pages
⚠️

Common Pitfalls

Common mistakes when filtering in Django include:

  • Using filter() when you want a single object; use get() instead.
  • Not using double underscores for lookups, causing errors or unexpected results.
  • Forgetting that filter() returns a QuerySet, which can be empty but never None.
  • Chaining filters incorrectly, which can narrow results too much.
python
wrong = Book.objects.filter(published_year=2010)  # Only books exactly in 2010
right = Book.objects.filter(published_year__gte=2010)  # Books from 2010 and later
📊

Quick Reference

Lookup TypeExampleDescription
Exact matchfilter(name='Alice')Finds objects where name is exactly 'Alice'
Greater thanfilter(age__gt=18)Finds objects with age greater than 18
Less than or equalfilter(score__lte=100)Finds objects with score less or equal to 100
Containsfilter(title__contains='Django')Finds objects where title contains 'Django'
Starts withfilter(name__startswith='J')Finds objects where name starts with 'J'

Key Takeaways

Use filter() with keyword arguments to get QuerySets matching conditions.
Use double underscores __ for advanced lookups like greater than or contains.
filter() returns a QuerySet that can be empty but never None.
For a single object, use get() instead of filter().
Chain multiple conditions inside filter() to narrow results.