Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Relationship Query Patterns in Django
📖 Scenario: You are building a simple library system. There are Authors and Books. Each book is written by one author. You want to practice how to query related data using Django's ORM.
🎯 Goal: Create Django models for Author and Book with a relationship. Then write queries to find all books by a specific author and all authors who have written books.
📋 What You'll Learn
Create a Django model Author with a name field
Create a Django model Book with a title field and a foreign key to Author
Write a query to get all books by the author named 'Jane Austen'
Write a query to get all authors who have written at least one book
💡 Why This Matters
🌍 Real World
Managing related data is common in web apps like libraries, blogs, or stores. Knowing how to query related models helps you build powerful features.
💼 Career
Django developers often work with related models. Mastering relationship queries is essential for backend development and data handling.
Progress0 / 4 steps
1
Create Author and Book models
Create a Django model called Author with a name field as models.CharField(max_length=100). Also create a model called Book with a title field as models.CharField(max_length=200) and a foreign key called author to Author using models.ForeignKey(Author, on_delete=models.CASCADE).
Django
Hint
Remember to import models from django.db. Use models.CharField for text fields and models.ForeignKey for relationships.
2
Set author name to query
Create a variable called author_name and set it to the string 'Jane Austen'. This will be used to find books by this author.
Django
Hint
Just create a variable author_name and assign the exact string 'Jane Austen'.
3
Query books by author name
Write a Django ORM query to get all Book objects where the related author's name matches the variable author_name. Assign the result to a variable called books_by_author.
Django
Hint
Use double underscores author__name to filter books by the author's name.
4
Query authors with books
Write a Django ORM query to get all Author objects who have written at least one book. Assign the result to a variable called authors_with_books. Use distinct() to avoid duplicates.
Django
Hint
Use book__isnull=False to find authors with books and add distinct() to avoid duplicates.
Practice
(1/5)
1. In Django, how do you filter a queryset to get all Book objects where the related Author model's name is 'Alice'?
easy
A. Book.objects.filter(author.name='Alice')
B. Book.objects.filter(name__author='Alice')
C. Book.objects.filter('author.name'='Alice')
D. Book.objects.filter(author__name='Alice')
Solution
Step 1: Understand Django's double underscore syntax for related fields
In Django ORM, to filter by a related model's field, use double underscores between the related model name and the field name.
Step 2: Apply the correct filter syntax
Here, author__name='Alice' correctly filters books whose author's name is 'Alice'.
Final Answer:
Book.objects.filter(author__name='Alice') -> Option D
Quick Check:
Related field filter uses __ = A [OK]
Hint: Use double underscores to filter related model fields [OK]
Common Mistakes:
Using dot notation instead of double underscores
Reversing the field and model names
Passing strings incorrectly in filter
2. Which of the following is the correct syntax to use select_related to optimize a query fetching Book objects with their related Author data?
easy
A. Book.objects.select_related(['author']).all()
B. Book.objects.select_related(author).all()
C. Book.objects.select_related('author').all()
D. Book.objects.select_related('author__name').all()
Solution
Step 1: Recall the correct argument type for select_related
select_related accepts one or more string arguments naming related fields to follow.
Step 2: Check the syntax for passing related field names
Passing a string like 'author' is correct. Passing a variable without quotes or a list is incorrect.
Final Answer:
Book.objects.select_related('author').all() -> Option C
Quick Check:
select_related takes string field names [OK]
Hint: Pass related field names as strings to select_related [OK]
Common Mistakes:
Passing variables without quotes
Using lists instead of strings
Including field names beyond direct relations
3. Given these models:
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Assuming Author has a reverse relation books to Book.
medium
A. No error, the query is correct
B. The lookup 'author__books' is invalid for prefetch_related
C. prefetch_related requires a list, not a string
D. prefetch_related cannot follow reverse relations
Solution
Step 1: Understand prefetch_related capabilities
prefetch_related supports double-underscore chained lookups across forward (FK) and reverse relations.
Step 2: Validate the lookup 'author__books'
From Book, 'author' follows the FK to Author, then 'books' follows the reverse relation to Book objects. This is valid and prefetches all books per author.
Final Answer:
No error, the query is correct -> Option A
Quick Check:
prefetch_related supports FK + reverse chains [OK]
Hint: prefetch_related supports chained lookups including reverse relations [OK]
Common Mistakes:
Thinking prefetch_related cannot chain to reverse relations
5. You want to efficiently fetch all Book objects along with their Author and the Publisher related to the author. The models are:
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 query optimizes database hits best?
hard
A. Book.objects.select_related('author', 'author__publisher').all()
B. Book.objects.prefetch_related('author', 'author__publisher').all()
C. Book.objects.select_related('author').prefetch_related('author__publisher').all()
D. Book.objects.all()
Solution
Step 1: Understand select_related vs prefetch_related
select_related follows foreign keys with SQL JOINs, efficient for single-valued relations. prefetch_related is for many-to-many or reverse relations.
Step 2: Analyze the relations
Both author and author__publisher are foreign keys (single-valued), so select_related is best to reduce queries.
Final Answer:
Book.objects.select_related('author', 'author__publisher').all() -> Option A
Quick Check:
Use select_related for foreign keys chains [OK]
Hint: Use select_related for foreign key chains to reduce queries [OK]