Bird
0
0

Consider this code:

medium📝 component behavior Q5 of 15
Django - Caching
Consider this code:
books = Book.objects.all()
for book in books:
    print(book.author.name)

What is the main problem with this code if select_related is not used?
AIt will execute one query per book to fetch the author.
BIt will raise a syntax error.
CIt will fetch all authors in a single query.
DIt will not fetch any authors.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze query behavior without select_related

    Without select_related, accessing book.author triggers a separate query per book.

  2. Step 2: Understand impact on performance

    This causes many queries, slowing down the app (N+1 query problem).

  3. Final Answer:

    It will execute one query per book to fetch the author. -> Option A
  4. Quick Check:

    No select_related = many queries [OK]
Quick Trick: Without select_related, related access causes many queries [OK]
Common Mistakes:
MISTAKES
  • Thinking it raises syntax errors
  • Assuming authors are fetched in one query automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes