0 day streak
python / intermediate
Snippet

Django ORM QuerySet Chaining and Aggregation

Django QuerySets support method chaining for building complex queries. select_related() performs SQL joins for ForeignKey relationships (single query), while prefetch_related() optimizes ManyToMany with separate queries. Aggregation functions like Count and Avg compute statistics. Q objects build complex OR/AND conditions. Custom Managers encapsulate reusable query logic, keeping models clean and testable.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django.db.models import Count, Avg, Q, F, Prefetch
from django.db.models.functions import TruncMonth
class BookManager(models.Manager):
def get_published_with_authors(self):
return self.get_queryset().filter(
is_published=True
).select_related('author').prefetch_related(
Prefetch('collaborators', queryset=Author.objects.only('id', 'name'))
)
def monthly_publication_stats(self):
return self.get_queryset().filter(
is_published=True
).annotate(
month=TruncMonth('published_date')
).values('month').annotate(
book_count=Count('id'),
avg_rating=Avg('rating')
).order_by('-month')
def search_books(self, query, min_rating=None):
filters = Q(title__icontains=query) | Q(description__icontains=query)
if min_rating:
filters &= Q(rating__gte=min_rating)
return self.filter(filters)
# Usage
books = Book.objects.search_books('python', min_rating=4.0)
top_rated = books.order_by('-rating')[:5]
django
Breakdown
1
select_related('author')
Fetches ForeignKey relations in a single SQL JOIN, avoiding N+1 queries
2
Prefetch('collaborators', queryset=...)
Optimizes ManyToMany with separate query, limiting fields to only what's needed
3
Q(title__icontains=query) | Q(description__icontains=query)
Q objects combine conditions with OR; & for AND, ~ for NOT
4
TruncMonth('published_date')
Truncates datetime to month for grouping publications by month