[Fixed]-Django โ€“ Loading Many-To-Many relationship admin page is so slow

14๐Ÿ‘

โœ…

If you still want to use limit_choices_to, then please refer to the docs. You basically just supply the filters in a dictionary object.

To speed up the admin, my suggestions include:
1. Using raw_id_fields in your ModelAdmin. This gives you a little searchbox instead of a selectbox and avoids the overhead of listing all related objects.
2. If you are handling forward ForeignKey relationships, you can use list_select_related in your ModelAdmin as well. In your case, you are handling many-to-many relationships, so you can try overriding the get_queryset method of the ModelAdmin, and use prefetch_related like in the code below.

from django.contrib import admin

class TestModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        test_model_qs = super(TestModelAdmin, self).get_queryset(request)
        test_model_qs = test_model_qs.prefetch_related('many-to-many-field')
        return test_model_qs

If you really like to get your hands dirty, I highly recommend you use django-debug-toolbar. It really gives you visibility on how many and what SQL statements are being run. If you can read SQL, you can deduce what you need to input to select_related and prefetch_related.

๐Ÿ‘คWannabe Coder

Leave a comment