在关于select related的Django Admin文档中,代码示例指定list_select_related = ('authors', )
的声明将有助于防止N + 1问题。
我试图将其用于下面定义的一组模型:
class Grouping(models.Model):
name = models.CharField(max_length=128, null=False)
class InsightCondition(models.Model):
criterion = models.CharField(max_length=256, db_index=True)
description = models.CharField(max_length=256, db_index=True)
class Insight(models.Model):
my_other_thing = models.CharField(max_length=128, null=False)
grouping = models.ForeignKey('Grouping', related_name="insights", blank=False, null=False)
condition = models.ForeignKey('InsightCondition', related_name='insights', null=True, blank=True)
当尝试使用Django管理员解散时,我仍然在日志中看到n + 1问题。为了解决这个问题,我将list_select_related = ('insights', )
添加到以下类中:
@admin.register(Insight)
class InsightAdmin(admin.ModelAdmin):
list_display = ('condition_link', 'uid', 'grouping_link',
'detail_description', 'state', )
list_filter = ('grouping', 'condition')
list_select_related = ('grouping', 'condition')
grouping_link = easy.ForeignKeyAdminField('grouping')
condition_link = easy.ForeignKeyAdminField('condition')
pass
@admin.register(Grouping)
class GroupingAdmin(admin.ModelAdmin):
list_display = ('name', 'insight_count')
search_fields = ['name', 'insights__uid']
list_select_related = ('insights', )
def insight_count(self, group):
return group.insights.count()
pass
@admin.register(InsightCondition)
class InsightConditionAdmin(admin.ModelAdmin):
list_display = ('criterion', 'description', )
search_fields = ('criterion', 'description', )
# Failing Lines ....
list_select_related = (
'insights',
)
select_related = ('insights', )
pass
在管理网站上加载时,我收到错误
FieldError at /admin/insights/insightcondition/
Invalid field name(s) given in select_related: 'insights'. Choices are: (none)
的完整错误
我想到这可能是安装软件包的问题所以我已经包含了以下内容:
bleach (2.0.0)
coverage (4.4.1)
decorator (4.1.1)
Django (1.11.2)
django-admin-easy (0.3.2)
django-debug-toolbar (1.8)
django-extensions (1.8.1)
django-fsm (2.6.0)
django-reversion (2.0.9)
djangorestframework (3.6.3)
entrypoints (0.2.3)
honeybadger (0.0.6)
html5lib (0.999999999)
ipykernel (4.6.1)
ipython (6.1.0)
ipython-genutils (0.2.0)
ipywidgets (6.0.0)
jedi (0.10.2)
Jinja2 (2.9.6)
jsonschema (2.6.0)
jupyter (1.0.0)
jupyter-client (5.1.0)
jupyter-console (5.1.0)
jupyter-core (4.3.0)
lxml (3.8.0)
MarkupSafe (1.0)
mistune (0.7.4)
nbconvert (5.2.1)
nbformat (4.3.0)
newrelic (2.88.1.73)
notebook (5.0.0)
pandocfilters (1.4.1)
pexpect (4.2.1)
pickleshare (0.7.4)
pip (9.0.1)
prompt-toolkit (1.0.14)
psutil (5.2.2)
ptyprocess (0.5.2)
pyaml (16.12.2)
Pygments (2.2.0)
python-dateutil (2.6.1)
pytz (2017.2)
PyYAML (3.12)
pyzmq (16.0.2)
qtconsole (4.3.0)
setuptools (36.2.0)
simplegeneric (0.8.1)
six (1.10.0)
sqlparse (0.2.3)
tblib (1.3.2)
terminado (0.6)
testpath (0.3.1)
tornado (4.5.1)
traitlets (4.3.2)
wcwidth (0.1.7)
webencodings (0.5.1)
wheel (0.29.0)
widgetsnbextension (2.0.0)
任何帮助都将受到赞赏,因为N + 1是数据库上的谋杀以及加载时间。我假设我做了一些愚蠢或忽略了一些应该是显而易见的事情。