在这种情况下,为什么Django管理员list_select_related不起作用? [英] Why does Django admin list_select_related not work in this case?

查看:66
本文介绍了在这种情况下,为什么Django管理员list_select_related不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ModelAdmin 类,该类的 list_display 中包含一个外键字段.但是该模型的管理员列表页面正在执行数百个查询,每行一个查询从另一张表中获取数据,而不是联接( select_related()).

I've got a ModelAdmin class that includes a foreign key field in its list_display. But the admin list page for that model is doing hundreds of queries, one query per row to get the data from the other table instead of a join (select_related()).

Django文档表示您可以将 list_select_related = True 作为属性添加到您的ModelAdmin中,以使它消失,但是对我来说似乎根本不起作用.这个SO问题似乎也有类似的问题,但是他的解决方案尚不清楚,而且没有.就我而言不起作用.

The Django docs indicate you can add list_select_related = True as an attribute to your ModelAdmin to make this go away, but it doesn't seem to work at all for me. This SO question seems to give a similar problem, but his resolution is unclear, and it doesn't work in my case.

这是我的模型和模型管理员的简化版本:

Here's a cut-down version of my model and model admin:

class Device(models.Model):
    serial_number = models.CharField(max_length=80, blank=True, unique=True)
    label = models.CharField(max_length=80, blank=True)

    def __str__(self):
        s = str(self.serial_number)
        if self.label:
            s += ': {0}'.format(self.label)
        return s

class Event(models.Model):
    device = models.ForeignKey(Device, null=True)
    type = models.CharField(max_length=40, null=False, blank=True, default='')

class EventAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'device')
    list_select_related = True

但是,添加 list_selected_related = True 并没有改变任何内容.我仍然收到很多类似这样的查询,而不是SQL连接:

However, adding that list_selected_related = True didn't change anything. I still get lots of queries like this instead of an SQL join:

有什么主意,为什么Django管理员似乎忽略了我的list_select_related并执行了N个查询?我正在使用Python 2.7和Django 1.3.3.

Any ideas why the Django admin seems to be ignoring my list_select_related and doing N queries? I'm using Python 2.7 and Django 1.3.3.

推荐答案

此处的问题是,设置 list_select_related = True 只会在查询中添加基本的 select_related(),但默认情况下,该调用不会在外键后面加上 null = True .因此,答案是定义变更列表使用的查询集,并指定要遵循的FK:

The issue here is that setting list_select_related = True just adds a basic select_related() onto the query, but that call does not by default follow ForeignKeys with null=True. So the answer is to define the queryset the changelist uses yourself, and specify the FK to follow:

class EventAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'device')
    def queryset(self, request):
        return super(EventAdmin, self).queryset(request).select_related('device')

这篇关于在这种情况下,为什么Django管理员list_select_related不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆