0
0
Djangoframework~5 mins

Chaining querysets in Django

Choose your learning style9 modes available
Introduction

Chaining querysets lets you combine multiple database queries into one. This helps you get exactly the data you want step by step.

You want to filter a list of items first by one condition, then by another.
You want to reuse a base query and add more filters later.
You want to combine results from different queries without running them separately.
You want to keep your code clean by splitting complex queries into smaller parts.
Syntax
Django
queryset1 = Model.objects.filter(condition1)
queryset2 = queryset1.filter(condition2)
# You can chain more filters or other queryset methods
Each filter() returns a new queryset, so original querysets stay unchanged.
Querysets are lazy; chaining does not hit the database until you actually use the data.
Examples
First filter books by author, then chain to filter by year.
Django
books = Book.objects.filter(author='Alice')
books = books.filter(published_year=2023)
Chain filters to get recent books with high ratings.
Django
recent_books = Book.objects.filter(published_year__gte=2020)
popular_recent_books = recent_books.filter(rating__gte=4.5)
Chaining on an empty queryset still returns an empty queryset.
Django
empty_qs = Book.objects.none()
filtered_empty = empty_qs.filter(title__icontains='Python')
Be careful: slicing returns a list, not a queryset, so chaining filter after slicing will cause an error.
Django
all_books = Book.objects.all()
first_ten = all_books[:10]
filtered_slice = first_ten.filter(genre='Fiction')
Sample Program

This example shows how to chain querysets to narrow down results step by step. First, it gets all books by Alice. Then it chains another filter to get only those published in 2023.

Django
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    published_year = models.IntegerField()
    rating = models.FloatField()

# Assume we have some Book objects saved in the database

# Step 1: Get books by author 'Alice'
alice_books = Book.objects.filter(author='Alice')
print('Books by Alice:')
for book in alice_books:
    print(f'- {book.title} ({book.published_year})')

# Step 2: Chain to get books by Alice published in 2023
alice_books_2023 = alice_books.filter(published_year=2023)
print('\nBooks by Alice published in 2023:')
for book in alice_books_2023:
    print(f'- {book.title}')
OutputSuccess
Important Notes

Chaining querysets is efficient because Django combines all filters into one database query.

Querysets are lazy, so no database hit happens until you iterate or convert to list.

Common mistake: slicing a queryset returns a list, which cannot be chained further.

Summary

Chaining querysets lets you build complex queries step by step.

Each filter returns a new queryset without changing the original.

Be careful not to slice before filtering, or chaining will break.