DEV Community

Cover image for Fixing Slow Django Admin Pages on Large Tables
sizan mahmud0
sizan mahmud0

Posted on

Fixing Slow Django Admin Pages on Large Tables

The Django admin is fast on small tables and painful on big ones. Here's a quick checklist for getting it back under control.

Step 0: measure

Use django-debug-toolbar and check query count, duplicates, and the slowest query. For a suspicious query:

print(Order.objects.filter(status="paid").explain(analyze=True))
Enter fullscreen mode Exit fullscreen mode

N+1 in list_display

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ("id", "customer", "status", "total")
    list_select_related = ("customer",)
Enter fullscreen mode Exit fullscreen mode

For more control:

def get_queryset(self, request):
    return (
        super().get_queryset(request)
        .select_related("customer")
        .only("id", "status", "total", "customer__name")
    )
Enter fullscreen mode Exit fullscreen mode

Careful: if __str__ or a display method reads a field you excluded with only(), you get N+1 again.

Custom columns that query per row

from django.db.models import Count

def get_queryset(self, request):
    return super().get_queryset(request).annotate(_item_count=Count("items"))

@admin.display(ordering="_item_count", description="Items")
def item_count(self, obj):
    return obj._item_count
Enter fullscreen mode Exit fullscreen mode

Counts and pagination

list_per_page = 50
show_full_result_count = False
Enter fullscreen mode Exit fullscreen mode

Search

search_fields = ("^email", "=order_number", "name")
Enter fullscreen mode Exit fullscreen mode

^ is starts-with and = is exact match. A plain name keeps icontains, which can't use a B-tree index.

Giant dropdowns

autocomplete_fields = ("customer",)  # needs search_fields on the related admin
raw_id_fields = ("customer",)        # lightest option
Enter fullscreen mode Exit fullscreen mode

Inlines

class OrderItemInline(admin.TabularInline):
    model = OrderItem
    extra = 0
    max_num = 50
    raw_id_fields = ("product",)
    show_change_link = True
Enter fullscreen mode Exit fullscreen mode

Full guide

The complete post also covers filters, date_hierarchy, admin actions, a checklist, and an FAQ:

👉 https://blog.reiteachaigean.com/blog/fix-slow-django-admin-pages

Related reads:

What's your go-to fix for a slow admin page?

Top comments (0)