Steve K
Steve K

Reputation: 11369

Django admin : ModelAdmin with foreign key to User adds one query per row

An issue I have in Django admin : I created a ModelAdmin derived class. This class has an attribute list_select_related set to True.

If I add a foreign key field to the User model in list_display, whatever I do, every row displayed adds a query in the following form :

SELECT `auth_user`.`id`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`is_superuser`, `auth_user`.`last_login`, `auth_user`.`date_joined`, `auth_user`.`picture_id` FROM `auth_user` WHERE `auth_user`.`id` = 1

It makes the admin quite slow, what is going on ? Thanks in advance.

Upvotes: 3

Views: 832

Answers (1)

Steve K
Steve K

Reputation: 11369

Okay, I managed to resolve the issue. You have to be very specific in your code. You have to override ModelAdmin.queryset like this to prevent those extra useless queries from being run. This got the query count down from 286 to 7 (for a page of 100 items).

Editing ModelAdmin.queryset

class MyModelAdmin(ModelAdmin):
    def queryset(self, request):
        qs = super(AccessAdmin, self).queryset(request)
        qs = qs.select_related('user','ip','user__picture').only('user__username','path','referrer','ip__id','ip__string','ip__country','time','user__id','id','ip__ip','user__picture','user__picture__id','user__picture__image')
        return qs

You will have to select your fields and your foreign keys carefully. If you were wondering, the user.picture field was added with the Model.add_to_class method.

Upvotes: 1

Related Questions