Bird
0
0

Given these models:

medium📝 component behavior Q4 of 15
Django - Caching
Given these models:
class Publisher(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    publisher = models.ForeignKey(Publisher, related_name='books', on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

What will Publisher.objects.prefetch_related('books') do when iterating over publishers and accessing publisher.books.all()?
AIt will execute one query per publisher to fetch related books.
BIt will execute one query joining publishers and books with INNER JOIN.
CIt will execute only two queries: one for publishers and one for all related books.
DIt will not prefetch books and will execute queries lazily.
Step-by-Step Solution
Solution:
  1. Step 1: Understand prefetch_related behavior

    prefetch_related performs one query for main model and one for related model.
  2. Step 2: Effect on iteration

    Accessing publisher.books.all() uses cached related objects, no extra queries.
  3. Final Answer:

    It will execute only two queries: one for publishers and one for all related books. -> Option C
  4. Quick Check:

    prefetch_related batches queries, avoiding per-object queries [OK]
Quick Trick: prefetch_related runs two queries regardless of object count [OK]
Common Mistakes:
MISTAKES
  • Assuming prefetch_related uses SQL joins
  • Expecting one query per related object
  • Thinking prefetch_related delays queries until access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes