Bird
0
0

You have these models:

hard📝 Application Q15 of 15
Django - Caching
You have these models:
class Publisher(models.Model):
    name = models.CharField(max_length=100)

class Author(models.Model):
    name = models.CharField(max_length=100)
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

How do you optimize a query to get all books with their authors and authors' publishers in the fewest queries?
ABook.objects.select_related('author', 'author__publisher').all()
BBook.objects.select_related('author').select_related('publisher').all()
CBook.objects.prefetch_related('author', 'author__publisher').all()
DBook.objects.select_related('publisher').all()
Step-by-Step Solution
Solution:
  1. Step 1: Identify the related fields to join

    We want to fetch author and the publisher related to that author in one query.
  2. Step 2: Use nested select_related syntax

    Use select_related('author', 'author__publisher') to join both foreign keys in one query.
  3. Step 3: Evaluate other options

    Book.objects.select_related('author').select_related('publisher').all() is invalid because publisher is not directly on Book. Book.objects.prefetch_related('author', 'author__publisher').all() uses prefetch_related which is less efficient here. Book.objects.select_related('publisher').all() misses author relation.
  4. Final Answer:

    Book.objects.select_related('author', 'author__publisher').all() -> Option A
  5. Quick Check:

    Nested select_related joins = A [OK]
Quick Trick: Chain related fields with double underscores in select_related [OK]
Common Mistakes:
MISTAKES
  • Trying to select_related unrelated fields directly
  • Using prefetch_related instead of select_related for foreign keys
  • Missing nested relation syntax with double underscores

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes