Bird
0
0

Given these models:

hard📝 component behavior Q8 of 15
Django - Caching
Given 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)

Which select_related call will efficiently fetch Book objects with their related Author and Publisher in one query?
ABook.objects.select_related('publisher').all()
BBook.objects.select_related('author.publisher').all()
CBook.objects.prefetch_related('author', 'publisher').all()
DBook.objects.select_related('author', 'author__publisher').all()
Step-by-Step Solution
Solution:
  1. Step 1: Understand nested select_related

    To fetch related objects across multiple foreign keys, use double underscores to traverse relations.
  2. Step 2: Analyze options

    Book.objects.select_related('author', 'author__publisher').all() correctly uses 'author' and 'author__publisher' to join both related models. Book.objects.select_related('author.publisher').all() uses incorrect dot notation. Book.objects.prefetch_related('author', 'publisher').all() uses prefetch_related which is less efficient for ForeignKey. Book.objects.select_related('publisher').all() tries to select a non-existent direct field.
  3. Final Answer:

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

    Is nested relation syntax with double underscores correct? Yes. [OK]
Quick Trick: Use double underscores for nested select_related fields [OK]
Common Mistakes:
MISTAKES
  • Using dot notation instead of double underscores
  • Trying to select_related non-foreign key fields
  • Using prefetch_related for ForeignKey relations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes