Last Updated: February 25, 2016
· omouse

Fixing Slow Django Admin SQL Queries Caused by Inlines

In the past month at work we've been dealing with an issue in the Django Admin that has prevented our customer support team from editing customer data to make fixes and adjustments.

The Problem: Too Many Slow Queries

We found out that the inline model admins are the cause of too many slow queries. One of the edit pages took so long to load that the NGINX put up a request timed out page! To fix this, we investigated which inlines created the most SQL queries.

Here's our current code (roughly):

class MyModelAdmin(admin.ModelAdmin):
    inlines = [

These 3 extra admin inlines produced 27 queries.

Without those inlines, the model admin for MyModel only executed 7 queries.

The source of all these queries are the inlines, but the queries are also unfiltered.

The Workaround: Remove Inline model Admins

The quickest fix was to remove all the inlines and to make sure that each of the inline models was registered in the django admin. This allowed our customer support team (and us developers) to access the model edit page and if we needed to do anything else, we could access a different admin page for each of the previously inlined models.

The Fix: Override get_queryset in InlineModelAdmin

If our team can't live without the inlined model admins, we'll deploy a permanent fix which is to override the get_queryset method to narrow down how many items appear in the inlines.

Adding filtering to the inline querysets would decrease load time, but we would still have a lot of SQL queries being executed (27 with inlines versus 7 without inlines).

class MyInlineModelAdmin(admin.InlineModelAdmin):
    def get_queryset(self, request):
        qs = super(MyInlineModelAdmin, self).get_queryset(request)
        return qs.filter(owner=request.user)
Say Thanks