0
0
Djangoframework~10 mins

Database query optimization with select_related in Django - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Database query optimization with select_related
Start Query
Check for ForeignKey
Yes
Use select_related
Single SQL Join Query
Fetch Related Data Together
Return Optimized Result
End
The flow shows how select_related checks for foreign keys and fetches related data in one SQL query using joins, improving performance.
Execution Sample
Django
books = Book.objects.select_related('author').all()
for book in books:
    print(book.title, book.author.name)
This code fetches books and their authors in one query, then prints each book's title and author's name.
Execution Table
StepActionSQL QueryResultNotes
1Call select_related('author')SELECT * FROM book JOIN author ON book.author_id = author.idQuery prepared with joinOne SQL query with join ready
2Execute querySame as aboveDatabase returns combined rowsData for book and author together
3Iterate over booksNo new queryAccess book.title and book.author.nameNo extra queries due to select_related
4Print outputNo queryPrints book title and author nameEfficient data access
5End iterationNo queryAll data processedNo additional DB hits
💡 All books and their authors fetched in one query, no extra queries triggered during iteration
Variable Tracker
VariableStartAfter QueryAfter Iteration 1After Iteration 2Final
booksQuerySet (not evaluated)List of Book objects with author loadedBook object 1 with authorBook object 2 with authorAll Book objects with authors
Key Moments - 2 Insights
Why does select_related reduce the number of queries?
Because select_related uses a SQL JOIN to fetch related objects in one query, as shown in execution_table step 1 and 2, avoiding separate queries per object.
What happens if we don't use select_related when accessing related fields?
Without select_related, each access to a related field triggers a new query, causing many queries during iteration, unlike the single query in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what SQL query is executed at step 2?
ASELECT * FROM book JOIN author ON book.author_id = author.id
BSELECT * FROM book
CSELECT * FROM author
DNo SQL query is executed
💡 Hint
Check the SQL Query column in execution_table row 2
At which step does the code avoid extra database queries when accessing author data?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the Result and Notes columns in execution_table row 3
If select_related was not used, how would the execution table change?
AThe initial query would include a JOIN
BNo queries would be executed
CMore queries would appear during iteration steps
DThe query would fetch unrelated data
💡 Hint
Refer to key_moments about queries triggered without select_related
Concept Snapshot
Use select_related('related_field') to fetch related objects in one SQL JOIN query.
This reduces the number of database queries during iteration.
Without it, accessing related fields triggers extra queries.
Ideal for ForeignKey and OneToOne relationships.
Improves performance by loading related data eagerly.
Full Transcript
This visual trace shows how Django's select_related optimizes database queries by using a SQL JOIN to fetch related objects in one query. Initially, select_related prepares a query joining the main and related tables. When executed, the database returns combined rows with all needed data. Iterating over the results accesses related fields without extra queries, making data retrieval efficient. Without select_related, each related field access would cause a new query, slowing down the app. This technique is best for ForeignKey or OneToOne relations to improve performance.