Challenge - 5 Problems
Relationship Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2: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()Attempts:
2 left
💡 Hint
Think about how the double underscore syntax works in Django ORM for related fields.
✗ Incorrect
The filter
book__title__icontains='django' looks for authors whose related books have titles containing 'django'. The distinct() removes duplicates if an author has multiple matching books.❓ state_output
intermediate2:00remaining
How many items are in the resulting queryset?
Consider these models:
Given 3 publishers and 5 books distributed among them, what is the count of this queryset?
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()Attempts:
2 left
💡 Hint
Count publishers who have at least one book starting with 'A'.
✗ Incorrect
The filter selects publishers with books whose titles start with 'A'. If 2 publishers have such books, the count is 2.
📝 Syntax
advanced2: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?Attempts:
2 left
💡 Hint
Use double underscores to traverse relationships in filters.
✗ Incorrect
Django ORM uses double underscores to access related model fields in filters. Option A is correct syntax.
🔧 Debug
advanced2: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')Attempts:
2 left
💡 Hint
Check the type expected by the __in lookup.
✗ Incorrect
The __in lookup expects an iterable like a list or tuple, but a string was given, causing a TypeError.
🧠 Conceptual
expert2:00remaining
Which option best describes the behavior of select_related in Django ORM?
What does
select_related do when querying related models?Attempts:
2 left
💡 Hint
Think about how to optimize queries to avoid multiple database hits.
✗ Incorrect
select_related uses SQL joins to get related objects in one query, improving performance by reducing queries.