Bird
0
0

Why does this code raise an error?

medium📝 Debug Q7 of 15
Django - Caching
Why does this code raise an error?
queryset = Book.objects.prefetch_related('author.books')
ABecause 'author.books' is a nested prefetch and requires Prefetch object.
BBecause prefetch_related does not accept strings with dots.
CBecause 'author' is not a reverse relation.
DBecause Book model has no 'author' field.
Step-by-Step Solution
Solution:
  1. Step 1: Understand nested prefetching

    To prefetch nested relations like 'author.books', you must use Prefetch objects.
  2. Step 2: Check prefetch_related argument rules

    Simple strings cannot express nested prefetch; this causes an error.
  3. Final Answer:

    Because 'author.books' is a nested prefetch and requires Prefetch object. -> Option A
  4. Quick Check:

    Nested prefetch needs Prefetch object = B [OK]
Quick Trick: Use Prefetch objects for nested reverse relation prefetching [OK]
Common Mistakes:
MISTAKES
  • Passing nested relations as simple strings
  • Assuming prefetch_related accepts dotted strings
  • Confusing forward and reverse relations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes