Search code examples
pythondjangodjango-modelsdjango-admindjango-orm

Django admin is very slow when loading from the OneToOne user model


I think I am doing admin model wrong because it is taking like 30 seconds to load and I think its because my sql queries are too inefficient and there may be creating more look ups than needed. Is there a way that I can speed this up?

class UserInformationAdmin(admin.ModelAdmin):
    list_display = (
        'user_username',
        'user_first_name',
        'user_last_name',
        'major'
    )

    @admin.display(description='user.username')
    def user_username(self, obj):
        try:
            return obj.user.username
        except Exception:
            return None

    @admin.display(description='user.first_name')
    def user_first_name(self, obj):
        try:
            return obj.user.first_name
        except Exception:
            return None

    @admin.display(description='user.last_name')
    def user_last_name(self, obj):
        return obj.user.last_name```

Solution

  • From what I can understand having

        list_select_related = True
    

    convert the queries to a select_related queries, which are much faster. Here was the ultimate code that essentially worked.

    class UserInformationAdmin(admin.ModelAdmin):
        list_select_related = True
        
        list_display = (
            'user_username',
            'user_first_name',
            'user_last_name',
            'major'
        )
    
        @admin.display(description='user.username')
        def user_username(self, obj):
            try:
                return obj.user.username
            except Exception:
                return None
    
        @admin.display(description='user.first_name')
        def user_first_name(self, obj):
            try:
                return obj.user.first_name
            except Exception:
                return None
    
        @admin.display(description='user.last_name')
        def user_last_name(self, obj):
            return obj.user.last_name```