ExamHoot

Analyzing N+1 Query Problem in Django ORM

from myapp.models import Author, Book

# Approach 1
authors = Author.objects.all()
for author in authors:
    books = Book.objects.filter(author=author)
    print(f"{author.name}: {books.count()} books")

# Approach 2
authors = Author.objects.prefetch_related('book_set')
for author in authors:
    print(f"{author.name}: {author.book_set.count()} books")
  1. Approach 1 executes N+1 queries, while Approach 2 executes only 2 queries total.

  2. Both approaches execute the same number of queries because they fetch the same data.

  3. Approach 1 is more efficient because it uses direct filtering instead of prefetch_related().

  4. Approach 2 causes an N+1 problem because prefetch_related() executes a query for each author.

Show answer & explanation

Correct answer

Approach 1 executes N+1 queries, while Approach 2 executes only 2 queries total.

Explanation

Approach 1 causes N+1 queries (1 for authors + N for each author's books). Approach 2 uses prefetch_related() to fetch all books in a second query, reducing total queries from N+1 to 2.

Written by ExamHoot EditorialPublished · Updated

All 40 Django ORM Queries and QuerySets questions

  1. 1.What is a QuerySet in Django ORM?
  2. 2.Which method is used to retrieve all objects from a model?
  3. 3.What does the `filter()` method return in Django ORM?
  4. 4.What is the difference between `filter()` and `get()` methods?
  5. 5.What does the `exclude()` method do in Django ORM?
  6. 6.How do you order QuerySet results in Django?
  7. 7.What does `count()` method return?
  8. 8.What is QuerySet slicing used for?
  9. 9.What does `exists()` method do?
  10. 10.What does the `distinct()` method do?
  11. 11.Understanding Django QuerySet Evaluation
  12. 12.Filtering Related Objects with select_related()
  13. 13.Scenario:
  14. 14.Understanding F() Objects in Django ORM
  15. 15.Aggregation with Django ORM
  16. 16.Scenario:
  17. 17.Understanding Prefetch_related() for Reverse Relations
  18. 18.Query Chaining and Method Order
  19. 19.Using values() vs values_list()
  20. 20.Scenario:
  21. 21.Understanding QuerySet Lazy Evaluation and Database Queries
  22. 22.Scenario:
  23. 23.Analyzing N+1 Query Problem in Django ORM
  24. 24.QuerySet Method Chaining and Filter Behavior
  25. 25.Scenario:
  26. 26.Understanding QuerySet Slicing and Caching Behavior
  27. 27.Aggregation and Annotation in Django ORM
  28. 28.Scenario:
  29. 29.Understanding F Objects and Database-Level Operations
  30. 30.Scenario:
  31. 31.Complex Query with Multiple Aggregations and Filtering
  32. 32.Scenario:
  33. 33.Understanding Subqueries and Exists()
  34. 34.Raw SQL Queries and Security
  35. 35.Case-Insensitive Lookups and Performance
  36. 36.Scenario:
  37. 37.Understanding Query Caching and Database Hits
  38. 38.Bulk Operations:
  39. 39.Scenario:
  40. 40.Understanding Query Optimization with explain()