python / expert
Snippet
Django Custom Template Tags with Complex Data Aggregation
This snippet demonstrates creating a custom Django inclusion tag that performs complex database aggregation and passes structured data to a template for rendering. The tag uses annotation to calculate multiple metrics (count, average, sum) in a single database query, reducing N+1 query problems. The takes_context=True parameter allows access to request-specific data for permission filtering.
snippet.py
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
31
32
33
34
from django import templatefrom django.db.models import Count, Avg, Sumfrom django.utils.html import format_htmlregister = template.Library()@register.inclusion_tag('analytics/chart_data.html', takes_context=True)def render_category_analytics(context, queryset):"""Aggregates category data for chart rendering with filtering."""aggregated = (queryset.values('category__name', 'category__color').annotate(total_count=Count('id'),avg_rating=Avg('rating'),total_revenue=Sum('price')).order_by('-total_count'))chart_data = [{'label': item['category__name'],'color': item['category__color'],'datasets': [{'metric': 'Count', 'value': item['total_count'], 'formatted': f"{item['total_count']:,}"},{'metric': 'Avg Rating', 'value': round(item['avg_rating'] or 0, 2), 'formatted': f"{item['avg_rating']:.1f}" if item['avg_rating'] else 'N/A'},{'metric': 'Revenue', 'value': item['total_revenue'] or 0, 'formatted': f"${item['total_revenue']:,.2f}" if item['total_revenue'] else '$0.00'}]}for item in aggregated]return {'chart_data': chart_data, 'total_categories': len(chart_data)}
django
Breakdown
1
@register.inclusion_tag('analytics/chart_data.html', takes_context=True)
Decorator registers the function as an inclusion tag that renders using a separate template file
2
queryset.values('category__name', 'category__color')
Uses values() to group by category relationship fields, selecting only needed columns
3
.annotate(total_count=Count('id'), avg_rating=Avg('rating'), total_revenue=Sum('price'))
Performs aggregation with COUNT, AVG, and SUM operations in a single database query
4
chart_data = [{...} for item in aggregated]
List comprehension transforms raw aggregated results into chart-ready structured format
5
return {'chart_data': chart_data, 'total_categories': len(chart_data)}
Returns context dictionary that gets merged with parent context for template rendering