0
0
Djangoframework~20 mins

Aggregate and annotate methods in Django - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Aggregate and Annotate Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this Django ORM query output?
Given the following Django model and query, what will be the output of print(result)?
Django
from django.db import models
from django.db.models import Count

class Book(models.Model):
    title = models.CharField(max_length=100)

class Author(models.Model):
    name = models.CharField(max_length=100)
    books = models.ManyToManyField(Book)

# Query
result = Author.objects.annotate(num_books=Count('books')).values('name', 'num_books')
A[{'name': 'Alice', 'num_books': 3}, {'name': 'Bob', 'num_books': 0}]
B[{'name': 'Alice', 'num_books': 0}, {'name': 'Bob', 'num_books': 3}]
C[{'name': 'Alice', 'num_books': None}, {'name': 'Bob', 'num_books': None}]
DRaises a TypeError because Count cannot be used with ManyToManyField
Attempts:
2 left
💡 Hint
Think about how annotate with Count works on ManyToMany relationships.
📝 Syntax
intermediate
1:30remaining
Which option correctly annotates the average rating of books?
Given a Book model with a rating field, which Django ORM query correctly annotates each author with the average rating of their books?
Django
from django.db.models import Avg

# Choose the correct query:
AAuthor.objects.annotate(avg_rating=Avg('books__rating'))
BAuthor.objects.annotate(avg_rating=Avg('rating'))
CAuthor.objects.aggregate(avg_rating=Avg('books__rating'))
DAuthor.objects.annotate(avg_rating=Avg('book__rating'))
Attempts:
2 left
💡 Hint
Remember to use the related field name for the join.
🔧 Debug
advanced
2:00remaining
Why does this annotation produce incorrect counts?
Consider this query:
Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1)
It returns authors with 1 book instead of more than 1. Why?
ABecause Count counts duplicates due to joins; distinct=True is needed
BBecause filter should be applied before annotate, not after
CBecause num_books is not a valid annotation name
DBecause Count cannot be used with ManyToMany fields
Attempts:
2 left
💡 Hint
Think about SQL joins and duplicate rows.
🧠 Conceptual
advanced
1:30remaining
What is the difference between aggregate() and annotate()?
Which statement best describes the difference between aggregate() and annotate() in Django ORM?
A<code>aggregate()</code> modifies each object; <code>annotate()</code> returns a single summary
B<code>aggregate()</code> filters the queryset; <code>annotate()</code> sorts the queryset
C<code>aggregate()</code> can only be used with Count; <code>annotate()</code> can use any function
D<code>aggregate()</code> returns a single dictionary with summary values; <code>annotate()</code> adds summary values to each item in the queryset
Attempts:
2 left
💡 Hint
Think about the shape of the result each method returns.
state_output
expert
2:30remaining
What is the output of this complex annotation query?
Given these models and data, what will be the output of the query below? Models:
class Store(models.Model):
    name = models.CharField(max_length=100)

class Product(models.Model):
    store = models.ForeignKey(Store, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=6, decimal_places=2)

# Data:
# Store A has products priced 10.00, 20.00
# Store B has products priced 15.00

# Query:
from django.db.models import Max, F
result = Store.objects.annotate(
    max_price=Max('product__price'),
    discount_price=F('max_price') * 0.9
).values('name', 'max_price', 'discount_price').order_by('name')
Django
from django.db.models import Max, F

result = Store.objects.annotate(
    max_price=Max('product__price'),
    discount_price=F('max_price') * 0.9
).values('name', 'max_price', 'discount_price').order_by('name')
A[{'name': 'Store A', 'max_price': None, 'discount_price': None}, {'name': 'Store B', 'max_price': None, 'discount_price': None}]
B[{'name': 'Store A', 'max_price': 20.00, 'discount_price': 20.00}, {'name': 'Store B', 'max_price': 15.00, 'discount_price': 15.00}]
C[{'name': 'Store A', 'max_price': 20.00, 'discount_price': 18.00}, {'name': 'Store B', 'max_price': 15.00, 'discount_price': 13.50}]
DRaises a ValueError because F expressions cannot be multiplied by floats
Attempts:
2 left
💡 Hint
Check how F expressions work with arithmetic and aggregation.