Bird
0
0

What is wrong with this code snippet?

medium📝 Debug Q6 of 15
Django - Caching
What is wrong with this code snippet?
authors = Author.objects.prefetch_related(books)
for author in authors:
    print(author.books.all())
AThe loop should use select_related instead of prefetch_related.
BThe argument to prefetch_related should be a string, not a variable.
Cprefetch_related cannot be used on reverse relations.
Dauthor.books.all() is invalid syntax.
Step-by-Step Solution
Solution:
  1. Step 1: Check prefetch_related argument type

    The argument must be a string with the relation name, not a bare variable.
  2. Step 2: Confirm usage of prefetch_related on reverse relations

    prefetch_related works on reverse relations correctly.
  3. Final Answer:

    The argument to prefetch_related should be a string, not a variable. -> Option B
  4. Quick Check:

    prefetch_related argument must be string = C [OK]
Quick Trick: Always quote relation names in prefetch_related [OK]
Common Mistakes:
MISTAKES
  • Passing relation name without quotes
  • Confusing prefetch_related with select_related
  • Thinking author.books.all() is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes