Django QuerySet Filter
Filtering database records with powerful queries
🔎 What is filter()?
The filter() method returns a QuerySet containing objects that match your criteria. Unlike get(), it can return multiple objects and never raises exceptions if nothing is found.
# Filter books by author
from myapp.models import Book
books = Book.objects.filter(author="John Doe")
print(books)
Output:
<QuerySet [<Book: Python Guide>, <Book: Django Basics>]>
Key filter() Features
Multiple Results
Returns zero or more objects
books = Book.objects.filter(
published=True
)
Chainable
Combine multiple filters
books = Book.objects.filter(
published=True
).filter(price__lt=50)
Field Lookups
Powerful comparison operators
# Greater than, less than, etc.
books = Book.objects.filter(
price__gte=20
)
Safe
Returns empty QuerySet if no match
# No exception if not found
books = Book.objects.filter(
author="Unknown"
) # Returns empty QuerySet
🔹 Basic filter() Usage
The filter() method accepts keyword arguments where the key is the field name and the value is what you're searching for. You can filter by any field in your model.
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
published = models.BooleanField(default=False)
pages = models.IntegerField()
# views.py
from myapp.models import Book
# Filter by single field
published_books = Book.objects.filter(published=True)
# Filter by multiple fields
cheap_books = Book.objects.filter(published=True, price__lt=30)
for book in cheap_books:
print(f"{book.title} - ${book.price}")
Output:
Python Guide - $29.99
Django Basics - $24.99
🔹 Field Lookups
Django provides powerful field lookups using double underscores. These lookups let you perform comparisons like greater than, less than, contains, and many more without writing SQL.
from myapp.models import Book
# Exact match (default)
books = Book.objects.filter(author="John Doe")
# Case-insensitive exact match
books = Book.objects.filter(author__iexact="john doe")
# Contains
books = Book.objects.filter(title__contains="Python")
# Case-insensitive contains
books = Book.objects.filter(title__icontains="python")
# Starts with
books = Book.objects.filter(title__startswith="Django")
# Ends with
books = Book.objects.filter(title__endswith="Guide")
# Greater than
books = Book.objects.filter(price__gt=30)
# Less than or equal
books = Book.objects.filter(pages__lte=300)
Output:
<QuerySet [<Book: Python Guide>, <Book: Python Advanced>]>
🔹 Comparison Lookups
Use comparison operators to filter numeric and date fields. These lookups are essential for finding records within specific ranges or meeting certain thresholds.
from myapp.models import Book
# Greater than
expensive_books = Book.objects.filter(price__gt=50)
# Greater than or equal
books = Book.objects.filter(price__gte=30)
# Less than
cheap_books = Book.objects.filter(price__lt=20)
# Less than or equal
books = Book.objects.filter(pages__lte=200)
# Between (range)
mid_price_books = Book.objects.filter(price__range=(20, 40))
# In list
authors = ["John Doe", "Jane Smith", "Bob Wilson"]
books = Book.objects.filter(author__in=authors)
print(f"Found {expensive_books.count()} expensive books")
Output:
Found 5 expensive books
🔹 Chaining Filters
You can chain multiple filter() calls together to build complex queries. Each filter() returns a new QuerySet, allowing you to progressively narrow down your results.
from myapp.models import Book
# Chain multiple filters
books = Book.objects.filter(
published=True
).filter(
price__lt=50
).filter(
author__icontains="john"
)
# Same as above (more concise)
books = Book.objects.filter(
published=True,
price__lt=50,
author__icontains="john"
)
# Complex chaining
popular_books = Book.objects.filter(
published=True
).filter(
pages__gte=200
).filter(
price__range=(20, 60)
)
for book in popular_books:
print(book.title)
Output:
Python Guide
Django Basics
Web Development Pro
🔹 exclude() Method
The exclude() method is the opposite of filter() - it returns objects that don't match your criteria. You can combine filter() and exclude() for precise control.
from myapp.models import Book
# Exclude specific author
books = Book.objects.exclude(author="John Doe")
# Exclude multiple conditions
books = Book.objects.exclude(published=False, price__gt=100)
# Combine filter and exclude
affordable_books = Book.objects.filter(
published=True
).exclude(
price__gt=50
).exclude(
author="Unknown Author"
)
print(f"Found {affordable_books.count()} affordable books")
Output:
Found 12 affordable books