开发者

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

开发者 https://www.devze.com 2023-03-28 07:10 出处:网络
An issue I have in Django admin : I created a ModelAdmin derived class. This class has an attribute 开发者_JS百科list_select_related set to True.

An issue I have in Django admin : I created a ModelAdmin derived class. This class has an attribute 开发者_JS百科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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消