0
0
Djangoframework~10 mins

Aggregate and annotate methods in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to calculate the total number of books in the database using Django's ORM.

Django
from django.db.models import [1]
total_books = Book.objects.aggregate({"total": [1]('id')})
Drag options to blanks, or click blank then click option'
AAvg
BSum
CCount
DMax
Attempts:
3 left
💡 Hint
Common Mistakes
Using Sum instead of Count causes an error because IDs are not summed.
Using Avg or Max does not count the number of books.
2fill in blank
medium

Complete the code to annotate each author with the number of books they have written.

Django
from django.db.models import [1]
authors = Author.objects.annotate(book_count=[1]('book'))
Drag options to blanks, or click blank then click option'
AAvg
BSum
CMax
DCount
Attempts:
3 left
💡 Hint
Common Mistakes
Using Sum instead of Count will not count related books.
Using Avg or Max is not suitable for counting.
3fill in blank
hard

Fix the error in the code to get the average price of all books.

Django
from django.db.models import [1]
avg_price = Book.objects.aggregate(avg_price=[1]('price'))
Drag options to blanks, or click blank then click option'
ACount
BAvg
CMax
DSum
Attempts:
3 left
💡 Hint
Common Mistakes
Using Count or Sum returns wrong results or errors.
Using Max returns the highest price, not the average.
4fill in blank
hard

Fill both blanks to annotate each book with the total number of pages and filter books with more than 300 pages.

Django
from django.db.models import [1]
books = Book.objects.annotate(total_pages=[1]('pages')).filter(total_pages__[2]=300)
Drag options to blanks, or click blank then click option'
ASum
BCount
Cgt
Dlt
Attempts:
3 left
💡 Hint
Common Mistakes
Using Count instead of Sum for pages.
Using lt (less than) instead of gt (greater than) in filter.
5fill in blank
hard

Fill all three blanks to annotate authors with the maximum book price, minimum book price, and average book price.

Django
from django.db.models import [1], [2], [3]
authors = Author.objects.annotate(max_price=[1]('book__price'), min_price=[2]('book__price'), avg_price=[3]('book__price'))
Drag options to blanks, or click blank then click option'
AMax
BMin
CAvg
DCount
Attempts:
3 left
💡 Hint
Common Mistakes
Using Count instead of Min or Max.
Mixing up the order of functions.