DjangoPostgreSQLPerformanceBackend

Django Performance: From 8 Seconds to 340ms

How I diagnosed and fixed a slow Django dashboard using query analysis, select_related, prefetch_related, and strategic Redis caching.

11 min read

The 8-Second Dashboard

A client's admin dashboard was taking 8.2 seconds to load. Users were complaining. My first step was measurement.


Step 1: Diagnose with Django Debug Toolbar

``python

settings.py (dev only)

INSTALLED_APPS += ['debug_toolbar']

MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware']

`

The panel revealed 847 SQL queries on a single page load. Classic N+1 problem.


Step 2: Fix N+1 with select_related and prefetch_related

Before:

`python

orders = Order.objects.filter(status='pending')

for order in orders:

print(order.customer.name) # N+1: 1 query per order

print(order.items.all()) # N+1: 1 query per order

`

After:

`python

orders = (

Order.objects

.filter(status='pending')

.select_related('customer', 'customer__address') # JOINs for FK/OneToOne

.prefetch_related('items', 'items__product') # separate queries for M2M

.only('id', 'status', 'created_at', 'customer__name') # only fetch needed columns

)

`

Queries: 847 → 3. Load time: 8.2s → 1.1s.


Step 3: Add Database Indexes

`python

class Order(models.Model):

status = models.CharField(max_length=20)

customer = models.ForeignKey(Customer, on_delete=models.CASCADE)

created_at = models.DateTimeField(auto_now_add=True)

class Meta:

indexes = [

models.Index(fields=['status', 'created_at']),

models.Index(fields=['customer', 'status']),

]

`


Step 4: Redis Caching for Aggregates

Dashboard summary stats don't need to be real-time. Cache them.

`python

from django.core.cache import cache

def get_dashboard_stats(date_range: str) -> dict:

cache_key = f'dashboard_stats_{date_range}'

stats = cache.get(cache_key)

if stats is None:

stats = {

'total_orders': Order.objects.filter(...).count(),

'revenue': Order.objects.aggregate(total=Sum('amount'))['total'],

'active_customers': Customer.objects.filter(orders__created_at__gte=...).distinct().count(),

}

cache.set(cache_key, stats, timeout=300) # 5 minutes

return stats

``

Final result: 8.2s → 340ms (96% improvement)