Querysets
Filter, annotate and optimise database access instead of looping in Python.
What you will be able to do
- Chain filters to build a query.
- Use annotate for computed fields.
- Use select_related for foreign keys.
- Evaluate with list(), len() or iteration only when needed.
In plain English
A queryset is lazy: it builds SQL and runs when evaluated. Use filter, exclude, annotate and aggregate to let the database do the work. select_related and prefetch_related prevent the N+1 query problem.
from django.db.models import Count, Avg
from .models import Course
popular = (
Course.objects.annotate(lesson_count=Count('lessons'), avg_minutes=Avg('lessons__minutes'))
.filter(lesson_count__gte=5)
.order_by('-lesson_count')
)
for course in popular:
print(course.title, course.lesson_count, round(course.avg_minutes or 0, 1))Your turn
MediumAnnotate a count
Annotate courses with a lesson_count using Count("lessons").
PYTHON · starter
Course.objects.annotate()Check your understanding before moving on.
Knowledge checkQuestion 1
Which method prevents an N+1 query for a foreign key?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.