Bird
Raised Fist0
Djangoframework~20 mins

Relationship query patterns in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Relationship Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Django ORM query?
Given models Author and Book where Book has a ForeignKey to Author, what does this query return?

Author.objects.filter(book__title__icontains='django').distinct()
AA queryset of authors who have no books with 'django' in the title
BA queryset of books with 'django' in the title
CA queryset of all authors regardless of their books
DA queryset of authors who have at least one book with 'django' in the title, without duplicates
Attempts:
2 left
💡 Hint
Think about how the double underscore syntax works in Django ORM for related fields.
state_output
intermediate
2:00remaining
How many items are in the resulting queryset?
Consider these models:
class Publisher(models.Model): name = models.CharField(max_length=100)
class Book(models.Model): title = models.CharField(max_length=100); publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

Given 3 publishers and 5 books distributed among them, what is the count of this queryset?

Publisher.objects.filter(book__title__startswith='A').distinct().count()
A5
B3
C2
D0
Attempts:
2 left
💡 Hint
Count publishers who have at least one book starting with 'A'.
📝 Syntax
advanced
2:00remaining
Which option correctly uses Django ORM to get all books with authors named 'Alice'?
Given Book with ForeignKey author to Author, which query is correct?
ABook.objects.filter(author__name='Alice')
BBook.objects.filter(author.name='Alice')
CBook.objects.filter('author__name'='Alice')
DBook.objects.filter(author.name=='Alice')
Attempts:
2 left
💡 Hint
Use double underscores to traverse relationships in filters.
🔧 Debug
advanced
2:00remaining
What error does this Django ORM query raise?
Given models Category and Product where Product has ForeignKey category, what error occurs with this query?

Product.objects.filter(category__name__in='Electronics,Books')
ATypeError: argument of type 'str' is not iterable
BSyntaxError: invalid syntax
CNo error, returns products in categories 'Electronics' or 'Books'
DValueError: invalid lookup 'in' for CharField
Attempts:
2 left
💡 Hint
Check the type expected by the __in lookup.
🧠 Conceptual
expert
2:00remaining
Which option best describes the behavior of select_related in Django ORM?
What does select_related do when querying related models?
AIt fetches related objects lazily when accessed, causing additional queries
BIt performs a SQL join and fetches related objects in the same query to reduce database hits
CIt caches all related objects in memory for the entire application runtime
DIt deletes related objects automatically when the main object is deleted
Attempts:
2 left
💡 Hint
Think about how to optimize queries to avoid multiple database hits.

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

  1. 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.
  2. Step 2: Apply the correct filter syntax

    Here, author__name='Alice' correctly filters books whose author's name is 'Alice'.
  3. Final Answer:

    Book.objects.filter(author__name='Alice') -> Option D
  4. 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

  1. Step 1: Recall the correct argument type for select_related

    select_related accepts one or more string arguments naming related fields to follow.
  2. 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.
  3. Final Answer:

    Book.objects.select_related('author').all() -> Option C
  4. 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)

What will this query return?
books = Book.objects.filter(author__name__startswith='J')
medium
A. All authors whose name starts with 'J'
B. All books whose author's name starts with 'J'
C. All books with title starting with 'J'
D. Syntax error due to incorrect filter

Solution

  1. Step 1: Understand the filter condition

    The filter uses author__name__startswith='J', which means it looks at the related author's name starting with 'J'.
  2. Step 2: Determine the queryset result

    The queryset returns Book objects whose related Author name starts with 'J'.
  3. Final Answer:

    All books whose author's name starts with 'J' -> Option B
  4. Quick 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:
Book.objects.prefetch_related('author__books').all()

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

  1. Step 1: Understand prefetch_related capabilities

    prefetch_related supports double-underscore chained lookups across forward (FK) and reverse relations.
  2. 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.
  3. Final Answer:

    No error, the query is correct -> Option A
  4. 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
  • Passing a list instead of a string
  • Assuming prefetch_related cannot follow 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

  1. 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.
  2. Step 2: Analyze the relations

    Both author and author__publisher are foreign keys (single-valued), so select_related is best to reduce queries.
  3. Final Answer:

    Book.objects.select_related('author', 'author__publisher').all() -> Option A
  4. Quick 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