Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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```
like image 527
AugustusCaesar Avatar asked Nov 02 '25 17:11

AugustusCaesar


2 Answers

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```
like image 138
AugustusCaesar Avatar answered Nov 05 '25 09:11

AugustusCaesar


list_select_related = True

Keep this in the admin file when declaring model admin class.

like image 38
teja duluri Avatar answered Nov 05 '25 07:11

teja duluri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!