0
0
Djangoframework~10 mins

Prefetch_related for reverse relations in Django - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Prefetch_related for reverse relations
Query main model
Identify reverse relation
Create separate query for related objects
Fetch related objects in bulk
Link related objects to main model instances
Return combined result with prefetched data
Django fetches main model data first, then separately fetches related objects via reverse relation, and links them to avoid extra queries later.
Execution Sample
Django
authors = Author.objects.prefetch_related('book_set').all()
for author in authors:
    print(author.name, [book.title for book in author.book_set.all()])
Fetch authors and their related books efficiently using prefetch_related on reverse relation 'book_set'.
Execution Table
StepActionQuery ExecutedResultNotes
1Fetch all authorsSELECT * FROM author;List of authorsMain query to get authors
2Identify reverse relation 'book_set'N/APrepare to fetch booksRecognize reverse FK from Book to Author
3Fetch books for all authors in one querySELECT * FROM book WHERE author_id IN (author_ids);List of booksBulk fetch books related to authors
4Link books to each author instanceN/Aauthor.book_set populatedAttach books to authors in memory
5Iterate authors and print booksN/APrint author names and their book titlesNo extra queries during iteration
6EndN/AAll data fetched efficientlyPrefetch_related avoids N+1 query problem
💡 All authors and their related books fetched with only two queries, avoiding multiple database hits.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 4Final
authorsemptyList of Author objectsSame list, books not linked yetAuthors with book_set linkedAuthors with book_set linked
booksemptyemptyList of Book objects related to authorsBooks linked to authorsBooks linked to authors
Key Moments - 3 Insights
Why does prefetch_related run two queries instead of one?
Prefetch_related runs one query for the main model and a separate query for the related objects to efficiently fetch reverse relations in bulk, as shown in execution_table steps 1 and 3.
How does Django link the related objects to the main model after fetching?
After fetching related objects in step 3, Django attaches them to each main model instance in memory (step 4), so accessing reverse relations does not trigger new queries.
What problem does prefetch_related solve when accessing reverse relations?
It prevents the N+1 query problem where accessing each related set would cause a separate query, by fetching all related objects in one query and linking them upfront (see steps 3 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step are the related books fetched from the database?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Check the 'Query Executed' column for the step fetching books.
According to variable_tracker, when do authors get their book_set linked?
AAfter Step 4
BAfter Step 3
CAfter Step 1
DAt Start
💡 Hint
Look at the 'authors' row and see when book_set is populated.
If prefetch_related was not used, what would happen during iteration in Step 5?
ANo queries would run
BOne query for all books would run
CA query per author to fetch books would run
DAn error would occur
💡 Hint
Recall the N+1 query problem explained in key_moments.
Concept Snapshot
prefetch_related('reverse_relation') fetches related objects in a separate query.
It avoids multiple queries when accessing reverse foreign key sets.
Django runs two queries: one for main model, one for related objects.
Related objects are linked in memory for fast access.
Use it to improve performance when accessing reverse relations.
Full Transcript
This visual execution trace shows how Django's prefetch_related works for reverse relations. First, Django queries the main model (authors). Then it identifies the reverse relation (book_set) and fetches all related books in one query. After fetching, Django links these books to their respective authors in memory. This process avoids running a separate query for each author when accessing their books, solving the N+1 query problem. The variable tracker shows authors and books before and after linking. Key moments clarify why two queries run and how linking happens. The quiz tests understanding of when queries run and how data links. Overall, prefetch_related improves efficiency by batching related data fetching for reverse relations.