0
0
Djangoframework~10 mins

Chaining querysets in Django - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Chaining querysets
Start with first queryset
Apply filter or operation
Get second queryset
Chain with first queryset
Evaluate combined queryset
Return combined results
This flow shows how two or more querysets are combined by chaining filters or operations before evaluation.
Execution Sample
Django
qs1 = Book.objects.filter(author='Alice')
qs2 = Book.objects.filter(year__gte=2020)
combined_qs = qs1 | qs2
results = combined_qs.distinct()
This code chains two querysets to get books by author Alice or published from 2020 onwards, then removes duplicates.
Execution Table
StepActionQueryset StateResult Preview
1Create qs1 with filter author='Alice'qs1: SELECT * FROM Book WHERE author='Alice'Books by Alice
2Create qs2 with filter year >= 2020qs2: SELECT * FROM Book WHERE year >= 2020Books from 2020 or later
3Chain qs1 and qs2 with | operatorcombined_qs: qs1 OR qs2Books by Alice OR from 2020+
4Call distinct() on combined_qscombined_qs.distinct()Unique books matching either condition
5Evaluate combined_qs.distinct()Query runs on DBFinal list of unique books
6EndQuerysets evaluatedResults ready for use
💡 Querysets are lazy; evaluation happens at step 5 when results are needed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
qs1NoneQueryset filtered by author='Alice'SameSameSameSame
qs2NoneNoneQueryset filtered by year >= 2020SameSameSame
combined_qsNoneNoneNoneChained qs1 OR qs2distinct() appliedEvaluated results
Key Moments - 3 Insights
Why doesn't the database query run when we create or chain querysets?
Because Django querysets are lazy; they build the query but only run it when you actually need the data, like at step 5 in the execution table.
What does the | operator do when chaining querysets?
It combines two querysets with an OR condition, meaning results matching either queryset are included, as shown in step 3.
Why do we call distinct() after chaining querysets?
Because chaining with | can cause duplicates if some records appear in both querysets; distinct() removes these duplicates, as in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does combined_qs represent after step 3?
ABooks by Alice AND from 2020 or later
BBooks only by Alice
CBooks by Alice OR from 2020 or later
DBooks only from 2020 or later
💡 Hint
Check step 3 in the execution table where combined_qs is described as qs1 OR qs2.
At which step does the actual database query run?
AStep 5
BStep 3
CStep 2
DStep 1
💡 Hint
Look at the exit note and step 5 in the execution table where evaluation happens.
If we remove distinct() at step 4, what might happen to the results?
AResults will be empty
BResults may include duplicates
CResults will only include books by Alice
DResults will only include books from 2020 or later
💡 Hint
Refer to key moment about why distinct() is called after chaining.
Concept Snapshot
Chaining querysets lets you combine filters using operators like | (OR).
Querysets are lazy; queries run only when results are needed.
Use distinct() to remove duplicates after chaining.
Example: combined_qs = qs1 | qs2
Evaluate with list(combined_qs) or iteration.
Full Transcript
Chaining querysets in Django means combining two or more querysets to get results matching any of their conditions. Querysets are lazy, so creating or chaining them does not run a database query immediately. The | operator combines querysets with an OR condition. After chaining, duplicates can appear, so calling distinct() removes them. The actual database query runs only when you access the results, like iterating or converting to a list. This approach helps build complex queries step-by-step without hitting the database multiple times.