Exercise 3: Fixing a Page Listing with select_related — Possible Solution ==================================================================== THE CORRECTED QUERYSET ------------------------------ pages = Page.objects.filter(parent__isnull=False).select_related('parent') for p in pages: print(p.parent.title) WHAT PROBLEM select_related SOLVES ------------------------------ Per this chapter, without select_related, accessing p.parent.title inside the loop triggers a fresh, separate database query for every single row in pages - an N+1 pattern where N is the (potentially large and unbounded) number of pages in the listing. select_related('parent') instead fetches each page's related parent row via a real SQL JOIN, as part of the SAME single query that fetches the pages themselves. By the time the loop runs, every page object already has its parent's data attached - accessing p.parent.title inside the loop triggers no additional query at all, turning what would have been N+1 queries into exactly one. WHY THIS WORKS AS AN ANSWER ------------------------------ It provides a correct, working queryset using select_related('parent'), and correctly explains that it solves the N+1 problem by fetching the related row via a SQL JOIN in the original query rather than triggering a separate query per row during iteration.