Bird
0
0

You want to optimize a query that fetches Book objects and their related Author and Publisher objects, but Publisher is a ManyToMany field on Author. Which method should you use?

hard📝 Application Q9 of 15
Django - Caching
You want to optimize a query that fetches Book objects and their related Author and Publisher objects, but Publisher is a ManyToMany field on Author. Which method should you use?
AUse <code>select_related('author', 'author__publisher')</code>
BUse <code>prefetch_related('author__publisher')</code>
CUse <code>select_related('author')</code> only
DUse <code>filter(author__publisher__isnull=False)</code>
Step-by-Step Solution
Solution:
  1. Step 1: Identify relation types

    Publisher is ManyToMany on Author, so select_related cannot be used for it.

  2. Step 2: Choose correct optimization method

    prefetch_related is used for ManyToMany relations to fetch related objects efficiently.

  3. Final Answer:

    Use prefetch_related('author__publisher') -> Option B
  4. Quick Check:

    ManyToMany relations need prefetch_related [OK]
Quick Trick: Use prefetch_related for ManyToMany fields [OK]
Common Mistakes:
MISTAKES
  • Trying to use select_related on ManyToMany fields
  • Ignoring relation types when optimizing queries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes