Django admin performance issue

£可爱£侵袭症+ 提交于 2019-12-02 05:29:41

问题


I'm getting thousands of these queries when I try to open up a model in the Django admin interface and it's leading to a serious performance issue.

[sql] SELECT ... FROM `auth_user` WHERE `auth_user`.`id` = 9535
[sql] (21ms) Found 1 matching rows
[sql] SELECT ... FROM `auth_user` WHERE `auth_user`.`id` = 9536
[sql] (20ms) Found 1 matching rows

Any ideas why Django admin isn't using select_related()?

Here are (I think) the relevant parts of the model (I'm looking at an instance of the Student model in the admin):

from django.contrib.auth.models import User

class Student(models.Model):
    user = models.OneToOneField(User, unique=True)
    mhtl_user = models.OneToOneField(MHTLUser, unique=True)
    def __str__(self):
        return u"%s %s" % (self.user.first_name, self.user.last_name)

class MHTLUser(models.Model):
    user = models.OneToOneField(User, unique=True)
    def __str__(self):
        return str(self.user)

回答1:


Or just enable list_select_related.

class MyModelAdmin(admin.ModelAdmin):
    list_select_related = True
    # ....



回答2:


You could make Django use select_related by defining your own ModelAdmin like this

class MyModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        return qs.select_related()


来源:https://stackoverflow.com/questions/9719662/django-admin-performance-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!