Django admin change form load quite slow

Django now has support for autocomplete_fields which uses Select2 for input. You can configure as follows:

from django.contrib import admin

class RelationAdmin(admin.ModelAdmin):
       autocomplete_fields = ('Media','Particle',)

admin.site.register(Relation, RelationAdmin)

It is not the magic of django Orm. It is magic of Form. When you create a Foreign key in Model, then in ModelForm, a ModelChoiceField creates which has all choices of ForeignKey Model. And django Admin use all the properties of Form to create HTML. So use this code.

from django import forms
class RelationForm(forms.ModelForm):
    parent = forms.ChoiceField(required=False,
                              choices=Relation.objects.values_list('id', 'name'))
    particle = forms.ChoiceField(required=False,
                              choices=Particle.objects.values_list('id', 'content'))
    media = forms.ChoiceField(required=False,
                              choices=Media.objects.values_list('id', 'name'))

    class Meta:
        model = Relation 

In Admis Site

from django.contrib import admin
class RelationAdmin(admin.ModelAdmin):
    form = RelationForm
    model = Relation

You can also cache the choices pass in a form.


In admin.py

from django.contrib import admin

class RelationAdmin(admin.ModelAdmin):
       raw_id_fields = ('Media','Particle',)

admin.site.register(Relation, RelationAdmin)

This brings up a nice little UI element in the form and considerably improves performance since it doesn't have to load a huge number of options in the select box.


I'm willing to bet the issue is due to your ForeignKey. By default, django renders a <select> element for every foreign key.

If you have thousands of rows, this easily starts to bloat your HTML / DOM and I've noticed browsers starting to crap out at 20k items rendered in a <select> tag.

To fix it, look into overriding your admin form and not using the default widgets.