Build a fast Django dashboard: ORM aggregation with TruncDay, conditional and window functions, chart-ready JSON, versioned caching, summary tables refreshed by Celery, and Chart.js under a strict CSP.
Most dashboard performance problems come from doing aggregation in Python, scanning tables without a usable index, or recomputing the same numbers on every page load. This tutorial builds a sales dashboard in Django that avoids all three: aggregation in the database with the ORM, an endpoint shaped for charts, versioned caching with invalidation on writes, a pre-aggregated summary table for large data, and Chart.js rendering that works under a strict Content Security Policy.
Versions used: Python 3.13, Django 5.2.20 (5.2 LTS line), Celery 5.7.0 and Chart.js 4.6.2. Everything shown ran against SQLite in a project called myproject with an app called dashboard, seeded with 19,844 orders spread over 122 days, with one day (10 September) deliberately left empty. PostgreSQL differences are pointed out where they matter.
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
country = models.CharField(max_length=2)
class Order(models.Model):
class Status(models.TextChoices):
PAID = "paid"
REFUNDED = "refunded"
PENDING = "pending"
class Channel(models.TextChoices):
WEB = "web"
MOBILE = "mobile"
PARTNER = "partner"
customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name="orders")
status = models.CharField(max_length=10, choices=Status)
channel = models.CharField(max_length=10, choices=Channel)
amount = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField()
class Meta:
indexes = [
models.Index(fields=["created_at"], name="order_created_idx"),
models.Index(fields=["channel", "created_at"], name="order_channel_created_idx"),
]
permissions = [("view_sales_dashboard", "Can view the sales dashboard")]
class DailySales(models.Model):
day = models.DateField()
channel = models.CharField(max_length=10, choices=Order.Channel)
orders = models.PositiveIntegerField()
revenue = models.DecimalField(max_digits=14, decimal_places=2)
refunds = models.PositiveIntegerField()
refreshed_at = models.DateTimeField(auto_now=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=["day", "channel"], name="uniq_daily_sales"),
]
The custom permission view_sales_dashboard separates "may see revenue" from Django's generic model permissions. The two indexes match the filters the dashboard uses: a date range, optionally narrowed to one channel. In the composite index, the equality column comes first and the range column second, which is the order a B-tree can use for both.
Loading orders into Python and summing them in a loop moves every row over the wire. The ORM can express the whole aggregation as one GROUP BY query:
from datetime import datetime, time, timedelta
from decimal import Decimal
from django.db.models import Count, DateField, Q, Sum
from django.db.models.functions import TruncDay
from django.utils import timezone
from .models import DailySales, Order
def day_bounds(start, end):
"""Half-open datetime range [start 00:00, end+1 00:00) in the current time zone."""
tz = timezone.get_current_timezone()
return (
datetime.combine(start, time.min, tzinfo=tz),
datetime.combine(end + timedelta(days=1), time.min, tzinfo=tz),
)
def daily_rows(start, end, channel=""):
lower, upper = day_bounds(start, end)
qs = Order.objects.filter(created_at__gte=lower, created_at__lt=upper)
if channel:
qs = qs.filter(channel=channel)
return (
qs.annotate(day=TruncDay("created_at", output_field=DateField()))
.values("day")
.annotate(
orders=Count("id"),
revenue=Sum("amount", filter=Q(status=Order.Status.PAID), default=Decimal("0")),
refunds=Count("id", filter=Q(status=Order.Status.REFUNDED)),
)
.order_by("day")
)
The pattern is annotate() to compute the grouping key, values() to group by it, then annotate() again with aggregates. Points worth knowing:
filter=Q(...) computes several metrics in one pass instead of one query per status. Django emits SUM(...) FILTER (WHERE ...) on databases that support it (PostgreSQL and SQLite) and a CASE WHEN elsewhere.default=Decimal("0") wraps the sum in COALESCE, so a day with only refunds returns 0, not None.USE_TZ = True, TruncDay truncates in the current time zone. day_bounds() builds the range in the same zone, so a "day" means the same thing in the filter and in the grouping. output_field=DateField() returns plain dates instead of midnight datetimes.created_at >= lower AND created_at < upper, not created_at__date__range. The next section shows why.The generated SQL on SQLite, shortened:
SELECT django_date_trunc(day, "dashboard_order"."created_at", UTC, UTC) AS "day",
COUNT("dashboard_order"."id") AS "orders",
(CAST(COALESCE((CAST(SUM("dashboard_order"."amount")
FILTER (WHERE "dashboard_order"."status" = paid) AS NUMERIC)), ...)) AS "revenue",
COUNT("dashboard_order"."id") FILTER (WHERE "dashboard_order"."status" = refunded) AS "refunds"
FROM "dashboard_order"
WHERE ("dashboard_order"."created_at" >= 2026-09-08 00:00:00
AND "dashboard_order"."created_at" < 2026-09-13 00:00:00)
GROUP BY 1 ORDER BY 1 ASC
One SQLite quirk: sums of a DecimalField come back with extra digits, for example Decimal('17767.9700000000'). quantize() in the series builder normalises them; PostgreSQL returns numeric with the column's scale. Monthly totals work the same way with TruncMonth("created_at", output_field=DateField()), which returns the first day of each month.
Running totals and moving averages need window functions. Django 5.2 cannot apply a window over an aggregate of the same GROUP BY query:
.annotate(running=Window(Sum("revenue"), order_by=F("month").asc()))
django.core.exceptions.FieldError: Cannot compute Sum('revenue'): 'revenue' is an aggregate
Over the pre-aggregated summary table introduced later, where each row already is a day, it is straightforward:
from django.db.models import Avg, F, RowRange, Sum, Window
qs = (
DailySales.objects.filter(channel="web", day__range=(date(2026, 9, 8), date(2026, 9, 14)))
.annotate(
running_revenue=Window(Sum("revenue"), partition_by=[F("channel")],
order_by=F("day").asc()),
avg_7d=Window(Avg("orders"), partition_by=[F("channel")], order_by=F("day").asc(),
frame=RowRange(start=-6, end=0)),
)
.order_by("day")
.values("day", "orders", "revenue", "running_revenue", "avg_7d")
)
{'day': datetime.date(2026, 9, 8), 'orders': 98, 'revenue': Decimal('8784.02'), 'running_revenue': Decimal('8784.02000000000'), 'avg_7d': 98.0}
{'day': datetime.date(2026, 9, 9), 'orders': 82, 'revenue': Decimal('9018.72'), 'running_revenue': Decimal('17802.7400000000'), 'avg_7d': 90.0}
{'day': datetime.date(2026, 9, 11), 'orders': 93, 'revenue': Decimal('10615.13'), 'running_revenue': Decimal('28417.8700000000'), 'avg_7d': 91.0}
...
Two things to notice. The WHERE clause runs before the window, so the running total starts at the first day of the filter, not at the first order ever. And RowRange counts rows, not days: 10 September has no row, so the "7-day" average actually spans eight calendar days. Either store zero rows for empty days or fill gaps before computing moving averages.
QuerySet.explain() shows the plan without leaving Django. On SQLite:
>>> print(daily_rows(date(2026, 9, 8), date(2026, 9, 12)).explain())
8 0 163 SEARCH dashboard_order USING INDEX order_created_idx (created_at>? AND created_at<?)
18 0 0 USE TEMP B-TREE FOR GROUP BY
>>> print(daily_rows(date(2026, 9, 8), date(2026, 9, 12), "web").explain())
8 0 49 SEARCH dashboard_order USING INDEX order_channel_created_idx (channel=? AND created_at>? AND created_at<?)
20 0 0 USE TEMP B-TREE FOR GROUP BY
>>> print(Order.objects.filter(created_at__date__gte=date(2026, 9, 8)).explain())
2 0 216 SCAN dashboard_order
The __date lookup wraps the column in a function, so the index on created_at cannot be used and the whole table is scanned. On PostgreSQL the same happens with a cast to date. Use explain(analyze=True, buffers=True) there to see actual row counts and pages read; those options are PostgreSQL-specific and actually execute the query.
The other classic is N+1: a "recent orders" table that prints the customer name issues one query per row. Measured with connection.queries:
without select_related: 21
with select_related: 1
def recent_orders(limit=20):
return (
Order.objects.select_related("customer")
.only("id", "amount", "status", "created_at", "customer__name")
.order_by("-created_at")[:limit]
)
only() limits the columns fetched; with select_related the related fields are named with the double-underscore path.
Charting libraries draw what they are given. If a day without orders is missing from the data, a line chart connects its neighbours and the gap disappears. daily_series() therefore returns exactly one entry per calendar day, in ascending order, with zeros for empty days:
def daily_series(start, end, channel="", source=daily_rows):
"""One entry per calendar day, including days without orders."""
found = {row["day"]: row for row in source(start, end, channel)}
series = []
day = start
while day <= end:
row = found.get(day, {})
series.append({
"day": day.isoformat(),
"orders": row.get("orders", 0),
"revenue": str(row.get("revenue", Decimal("0")).quantize(Decimal("0.01"))),
"refunds": row.get("refunds", 0),
})
day += timedelta(days=1)
return series
Money is serialised as a string with two decimals. JSON numbers are binary floats in most clients, and a string keeps the exact value for CSV export and display; the chart converts it with Number(). The API response for three days, one of them empty:
GET /dashboard/api/daily/?start=2026-09-09&end=2026-09-11&channel=web
{
"start": "2026-09-09",
"end": "2026-09-11",
"channel": "web",
"series": [
{"day": "2026-09-09", "orders": 82, "revenue": "9018.72", "refunds": 5},
{"day": "2026-09-10", "orders": 0, "revenue": "0.00", "refunds": 0},
{"day": "2026-09-11", "orders": 93, "revenue": "10615.13", "refunds": 7}
]
}
Filters live in the query string so every view of the dashboard has a URL that can be bookmarked and shared, and the CSV link can reuse it. A form validates them:
from datetime import timedelta
from django import forms
from django.utils import timezone
from .models import Order
MAX_RANGE_DAYS = 366
class DashboardFilterForm(forms.Form):
start = forms.DateField(required=False)
end = forms.DateField(required=False)
channel = forms.ChoiceField(choices=[("", "All")] + Order.Channel.choices, required=False)
def clean(self):
data = super().clean()
end = data.get("end") or timezone.localdate()
start = data.get("start") or end - timedelta(days=29)
if start > end:
raise forms.ValidationError("start must be on or before end", code="range_order")
if (end - start).days >= MAX_RANGE_DAYS:
raise forms.ValidationError(
f"range is limited to {MAX_RANGE_DAYS} days", code="range_too_long"
)
data["start"], data["end"] = start, end
return data
The maximum range is a guard against a single request asking for ten years of daily rows. Invalid input returns a 400 with machine-readable errors:
GET /dashboard/api/daily/?start=2026-09-11&end=2026-09-01
400 {"errors": {"__all__": [{"message": "start must be on or before end", "code": "range_order"}]}}
The simplest option is Django's per-view cache, cache_page(60 * 5). It caches the full response per URL. Two limitations make it a poor fit here. Because the permission check reads the session, the response carries Vary: Cookie, so every user gets a separate copy. And a new order is invisible until the timeout expires.
A low-level cache on the data, with versioned keys, avoids both:
from django.core.cache import cache
from django.db import transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from .models import Order
from .queries import daily_series
GENERATION_KEY = "dashboard:generation"
TIMEOUT = 15 * 60
def generation():
gen = cache.get(GENERATION_KEY)
if gen is None:
cache.add(GENERATION_KEY, 1, timeout=None)
gen = cache.get(GENERATION_KEY, 1)
return gen
def bump_generation():
try:
cache.incr(GENERATION_KEY)
except ValueError: # key missing or evicted
cache.set(GENERATION_KEY, 1, timeout=None)
def cached_daily_series(start, end, channel=""):
key = f"dashboard:daily:{start.isoformat()}:{end.isoformat()}:{channel or 'all'}"
version = generation()
data = cache.get(key, version=version)
if data is None:
data = daily_series(start, end, channel)
cache.set(key, data, TIMEOUT, version=version)
return data
@receiver([post_save, post_delete], sender=Order)
def invalidate_dashboard(sender, **kwargs):
transaction.on_commit(bump_generation)
How the invalidation works: every key is stored under the current generation number using the cache's version argument. A write to Order increments the generation, after which all old entries are simply never read again and expire on their own. There is no need to know which date ranges a write affected. transaction.on_commit delays the bump until the transaction commits, so a concurrent request cannot cache data from before the commit under the new generation.
The signal is connected in AppConfig.ready() by importing the module. Note that bulk_create() and QuerySet.update() do not send post_save; call bump_generation() explicitly after bulk imports.
In production the cache must be shared between processes. LocMemCache, used in the tests, is per process: a write handled by one worker would bump only that worker's generation. Use Django's built-in Redis backend:
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
}
}
With tens of millions of orders, even an indexed range query over a year reads millions of rows. The standard answer is a summary table with one row per day and channel, refreshed by a scheduled task. Old days rarely change, so the task only recomputes the last few days:
from datetime import timedelta
from decimal import Decimal
from celery import shared_task
from django.db import transaction
from django.db.models import Count, DateField, Q, Sum
from django.db.models.functions import TruncDay
from django.utils import timezone
from .models import DailySales, Order
from .queries import day_bounds
@shared_task
def refresh_daily_sales(days=3):
"""Recompute the last `days` days. Safe to run repeatedly."""
end = timezone.localdate()
start = end - timedelta(days=days - 1)
lower, upper = day_bounds(start, end)
rows = (
Order.objects.filter(created_at__gte=lower, created_at__lt=upper)
.annotate(day=TruncDay("created_at", output_field=DateField()))
.values("day", "channel")
.annotate(
orders=Count("id"),
revenue=Sum("amount", filter=Q(status=Order.Status.PAID), default=Decimal("0")),
refunds=Count("id", filter=Q(status=Order.Status.REFUNDED)),
)
)
objs = [DailySales(**row) for row in rows]
with transaction.atomic():
DailySales.objects.bulk_create(
objs,
update_conflicts=True,
unique_fields=["day", "channel"],
update_fields=["orders", "revenue", "refunds", "refreshed_at"],
)
# A (day, channel) that lost all its orders must not keep stale totals.
fresh = {(o.day, o.channel) for o in objs}
stale = [
pk
for pk, day, channel in DailySales.objects.filter(
day__range=(start, end)
).values_list("pk", "day", "channel")
if (day, channel) not in fresh
]
DailySales.objects.filter(pk__in=stale).delete()
return len(objs)
CELERY_BEAT_SCHEDULE = {
"refresh-daily-sales": {
"task": "dashboard.tasks.refresh_daily_sales",
"schedule": crontab(minute="*/15"),
"kwargs": {"days": 3},
},
}
bulk_create(update_conflicts=True, ...) is an upsert: INSERT ... ON CONFLICT (day, channel) DO UPDATE on PostgreSQL and SQLite. Running the task twice gives the same table, so overlapping runs and retries are harmless. The stale-row cleanup covers a day whose last order was deleted. Reading from the summary uses a query with the same output shape, so daily_series() accepts it as a source:
def summary_rows(start, end, channel=""):
"""Same shape as daily_rows(), read from the pre-aggregated table."""
qs = DailySales.objects.filter(day__range=(start, end))
if channel:
qs = qs.filter(channel=channel)
return (
qs.values("day")
.annotate(orders=Sum("orders"), revenue=Sum("revenue"), refunds=Sum("refunds"))
.order_by("day")
)
A common split is the summary table for complete days and the live query for today. For backfills, run the task once with a large days value. On PostgreSQL, a materialized view refreshed with REFRESH MATERIALIZED VIEW CONCURRENTLY is an alternative, at the cost of recomputing everything on each refresh.
import csv
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_GET
from .cache import cached_daily_series
from .forms import DashboardFilterForm
PERM = "dashboard.view_sales_dashboard"
def _filters(request):
form = DashboardFilterForm(request.GET)
if not form.is_valid():
return None, form
return form.cleaned_data, form
@require_GET
@permission_required(PERM, raise_exception=True)
def index(request):
filters, form = _filters(request)
series = cached_daily_series(**filters) if filters else []
return render(request, "dashboard/index.html", {"form": form, "series": series})
@require_GET
@permission_required(PERM, raise_exception=True)
def daily_api(request):
filters, form = _filters(request)
if filters is None:
return JsonResponse({"errors": form.errors.get_json_data()}, status=400)
return JsonResponse({
"start": filters["start"].isoformat(),
"end": filters["end"].isoformat(),
"channel": filters["channel"] or None,
"series": cached_daily_series(**filters),
})
@require_GET
@permission_required(PERM, raise_exception=True)
def daily_csv(request):
filters, form = _filters(request)
if filters is None:
return JsonResponse({"errors": form.errors.get_json_data()}, status=400)
name = f"daily-{filters['start']}-{filters['end']}.csv"
response = HttpResponse(content_type="text/csv; charset=utf-8")
response["Content-Disposition"] = f'attachment; filename="{name}"'
writer = csv.writer(response)
writer.writerow(["day", "orders", "revenue", "refunds"])
for row in cached_daily_series(**filters):
writer.writerow([row["day"], row["orders"], row["revenue"], row["refunds"]])
return response
raise_exception=True returns 403 instead of redirecting to the login page, which is the right behaviour for an API that a script calls. All three views share _filters() and cached_daily_series(), so the page, the JSON and the CSV can never disagree. If you add cache_page, put it below permission_required so the permission check always runs first.
The CSV export writes known numeric and date fields only. If you export free text such as customer names, prefix values starting with =, +, - or @ with a single quote to prevent formula injection in spreadsheet programs. For large raw exports, use StreamingHttpResponse with queryset.iterator(chunk_size=2000).
Content-Disposition: attachment; filename="daily-2026-09-09-2026-09-11.csv"
day,orders,revenue,refunds
2026-09-09,82,9018.72,5
2026-09-10,0,0.00,0
2026-09-11,93,10615.13,7
Download chart.umd.min.js from the Chart.js 4.6.2 release into static/vendor/chartjs/ and serve it yourself. No third-party script host, no extra origin in your policy, and the version only changes when you commit a new file. The template contains no inline JavaScript. Data goes in with the json_script filter, which escapes <, > and & so the JSON cannot close the tag:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sales dashboard</title>
<script src="{% static 'vendor/chartjs/chart.umd.min.js' %}" defer></script>
<script src="{% static 'dashboard/dashboard.js' %}" defer></script>
</head>
<body>
<form method="get" id="filters">
{{ form.as_div }}
<button type="submit">Apply</button>
</form>
<a href="{% url 'dashboard:daily-csv' %}?{{ request.GET.urlencode }}">Download CSV</a>
<canvas id="daily-chart" aria-label="Orders and revenue per day" role="img"></canvas>
{{ series|json_script:"daily-data" }}
</body>
</html>
<script id="daily-data" type="application/json">[{"day": "2026-09-09", "orders": 143, "revenue": "15254.57", "refunds": 8}, {"day": "2026-09-10", "orders": 0, "revenue": "0.00", "refunds": 0}]</script>
A type="application/json" block is data, not script, so CSP does not apply to it. The chart code lives in a static file:
"use strict";
document.addEventListener("DOMContentLoaded", () => {
const source = document.getElementById("daily-data");
const canvas = document.getElementById("daily-chart");
if (!source || !canvas) return;
const series = JSON.parse(source.textContent);
new Chart(canvas, {
type: "bar",
data: {
labels: series.map((row) => row.day),
datasets: [
{
type: "line",
label: "Revenue",
data: series.map((row) => Number(row.revenue)),
yAxisID: "revenue",
},
{
label: "Orders",
data: series.map((row) => row.orders),
yAxisID: "orders",
},
],
},
options: {
animation: false,
interaction: { mode: "index", intersect: false },
scales: {
orders: { type: "linear", position: "left", beginAtZero: true },
revenue: { type: "linear", position: "right", beginAtZero: true,
grid: { drawOnChartArea: false } },
},
},
});
});
Django 5.2 has no built-in CSP support, so a small middleware sets the header. Chart.js 4 does not inject <style> elements or use eval, so it works under script-src 'self' and style-src 'self'.
class ContentSecurityPolicyMiddleware:
POLICY = "; ".join([
"default-src 'self'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' data:",
"object-src 'none'",
"base-uri 'none'",
"frame-ancestors 'none'",
])
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response.headers.setdefault("Content-Security-Policy", self.POLICY)
return response
Add it near the top of MIDDLEWARE. To refresh the chart without a page reload, fetch the JSON endpoint from dashboard.js with the current query string and call chart.update(); connect-src 'self' is covered by default-src.
The tests use the test client with a user who has the permission, and assert behaviour that matters for a dashboard: gaps filled, filters validated, permissions enforced, cache hits and invalidation, CSV and JSON in agreement, and the summary table matching the live query.
# dashboard/tests.py (excerpt). setUpTestData() creates three orders on 1 and 3 September
# and a user with the view_sales_dashboard permission; setUp() clears the cache and logs in.
def test_series_fills_empty_days_in_order(self):
series = daily_series(date(2026, 9, 1), date(2026, 9, 3))
self.assertEqual([r["day"] for r in series], ["2026-09-01", "2026-09-02", "2026-09-03"])
self.assertEqual(series[0], {"day": "2026-09-01", "orders": 2, "revenue": "10.00", "refunds": 1})
self.assertEqual(series[1]["orders"], 0)
def test_permission_required(self):
self.client.force_login(self.other)
self.assertEqual(self.client.get(URL).status_code, 403)
self.client.logout()
self.assertEqual(self.client.get(URL).status_code, 403)
def test_second_request_is_served_from_cache(self):
self.client.get(URL)
# Session, user, user permissions, group permissions; no aggregation.
with self.assertNumQueries(4):
self.client.get(URL)
def test_cache_is_invalidated_on_write(self):
before = cached_daily_series(date(2026, 9, 1), date(2026, 9, 3))
with self.captureOnCommitCallbacks(execute=True):
order(2, "3.00")
after = cached_daily_series(date(2026, 9, 1), date(2026, 9, 3))
self.assertEqual(before[1]["orders"], 0)
self.assertEqual(after[1]["orders"], 1)
def test_summary_table_matches_live_query(self):
with mock.patch("django.utils.timezone.localdate", return_value=date(2026, 9, 3)):
refresh_daily_sales(days=3)
start, end = date(2026, 9, 1), date(2026, 9, 3)
self.assertEqual(
daily_series(start, end, source=summary_rows), daily_series(start, end)
)
$ python manage.py test dashboard
Found 11 test(s).
...........
----------------------------------------------------------------------
Ran 11 tests in 0.122s
OK
assertNumQueries(4) pins the cached path to session, user and two permission lookups. If a change makes the aggregation run again, the test fails. captureOnCommitCallbacks(execute=True) runs the on_commit hook inside the test transaction, which TestCase would otherwise never commit.
values(), annotate() and filter=Q(), not in Python loops.explain() confirms is used; list views use select_related.json_script; the CSP allows only 'self'.Found a mistake in this tutorial? Let us know and we will fix it.