Topic 07 / 40
Table Joins: select_related & prefetch_related
1. Deep Architecture
The N+1 query problem occurs when a query for N items makes N additional queries to fetch a related field. select_related runs a single SQL JOIN query, best for 1-to-1 or foreign key relationships. prefetch_related runs two SQL queries and maps the results together in Python, best for many-to-many or reverse foreign key lookups.
2. The Feynman Gatekeeper
[KNOWLEDGE CHECK] Compare the memory and query profiles of select_related and prefetch_related. When is one better than the other?
3. The Code
# Query with JOIN (select_related) and separate fetch + map (prefetch_related)
videos = Video.objects.select_related('author').prefetch_related('comments')
for video in videos:
print(video.author.email) # No extra query
print(video.comments.all()) # No extra query
4. The Funnel
Stat Level-Up: N+1 Slayer (Lvl 1).
Sanjaya Integration: Fetch videos and their creator metrics in a single optimized database scan.