Relationship query patterns help you get data connected between tables easily. They let you find related information without writing complex code.
Relationship query patterns in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
Model.objects.filter(related_model__field=value) Model.objects.get(pk=1).related_model_set.all()
Use double underscores (__) to follow relationships in queries.
Related objects can be accessed using the related model name plus '_set' by default.
Examples
Django
Book.objects.filter(author__name='Alice')
Django
author = Author.objects.get(pk=1)
author.book_set.all()Django
Comment.objects.filter(post__title__icontains='django')
Django
User.objects.filter(profile__age__gte=18)
Sample Program
This example shows how to create an author and two books linked to her. Then it queries all books where the author's name is 'Alice' and prints their titles.
Django
from django.db import 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) # Sample usage # Create an author and books alice = Author.objects.create(name='Alice') Book.objects.create(title='Django Basics', author=alice) Book.objects.create(title='Advanced Django', author=alice) # Query books by author name books_by_alice = Book.objects.filter(author__name='Alice') for book in books_by_alice: print(book.title)
Important Notes
Remember to use the related model's field names exactly as defined.
Using double underscores lets you go through multiple relationships, like book__author__name.
Accessing related objects backward uses relatedmodel_set unless you set related_name.
Summary
Relationship queries let you find connected data easily.
Use double underscores to follow links between models.
Access related objects forward and backward with simple patterns.
Practice
1. In Django, how do you filter a queryset to get all
Book objects where the related Author model's name is 'Alice'?easy
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 DQuick 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
Solution
Step 1: Recall the correct argument type for select_related
select_relatedaccepts 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 CQuick 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:
What will this query return?
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)What will this query return?
books = Book.objects.filter(author__name__startswith='J')
medium
Solution
Step 1: Understand the filter condition
The filter usesauthor__name__startswith='J', which means it looks at the related author's name starting with 'J'.Step 2: Determine the queryset result
The queryset returnsBookobjects whose relatedAuthorname starts with 'J'.Final Answer:
All books whose author's name starts with 'J' -> Option BQuick Check:
Filter on related field with startswith = A [OK]
Hint: Filter related fields with double underscores and lookups [OK]
Common Mistakes:
- Confusing filtering on book title instead of author name
- Thinking the query returns authors instead of books
- Misusing lookup syntax causing errors
4. Identify the error in this Django query:
Assuming
Book.objects.prefetch_related('author__books').all()Assuming
Author has a reverse relation books to Book.medium
Solution
Step 1: Understand prefetch_related capabilities
prefetch_relatedsupports double-underscore chained lookups across forward (FK) and reverse relations.Step 2: Validate the lookup 'author__books'
FromBook, 'author' follows the FK toAuthor, then 'books' follows the reverse relation toBookobjects. This is valid and prefetches all books per author.Final Answer:
No error, the query is correct -> Option AQuick 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
- Passing a list instead of a string
- Assuming prefetch_related cannot follow reverse relations
5. You want to efficiently fetch all
Which query optimizes database hits best?
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
Solution
Step 1: Understand select_related vs prefetch_related
select_relatedfollows foreign keys with SQL JOINs, efficient for single-valued relations.prefetch_relatedis for many-to-many or reverse relations.Step 2: Analyze the relations
Bothauthorandauthor__publisherare foreign keys (single-valued), soselect_relatedis best to reduce queries.Final Answer:
Book.objects.select_related('author', 'author__publisher').all() -> Option AQuick Check:
Use select_related for foreign keys chains [OK]
Hint: Use select_related for foreign key chains to reduce queries [OK]
Common Mistakes:
- Using prefetch_related for foreign keys
- Not chaining related fields in select_related
- Fetching all without optimization
