Django内联表单和选项字段会生成太多的数据库查询 [英] Django inline formsets and choicefields generate too many db queries

查看:257
本文介绍了Django内联表单和选项字段会生成太多的数据库查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个外键字段的模型,例如模型产品具有字段类型,级别,颜色,强度(仅仅是一般示例)。



然后我有一个页面来编辑所有产品一种给定类型的类型,使用产品作为一个内联格式集,并可以使用 extra = 10 添加其他产品的选项。



我发现非常奇怪的是,每次当我输出模板上的一个外键选择字段Django查询数据库获取选项(每次)。



例如:

  {%for form in formset%} 
{{form .level}}
{{form.color}}
{{form.intensity}}
{%endfor%}

有20个产品(和10个空的额外表单)上述代码问题30 select ... from ... ,颜色和强度共有90个查询(使用Django Debug Toolbar显示),其中3应该是足够的。这些选项不太可能改变中间请求,但即使他们确实不希望一些新添加的选项仅在最后的5个表单中出现。



有没有办法优化我的模型/表单/视图/模板,以便数据库不会像这样不必要的锤击?



-



免责声明:我对django和python来说比较新,不禁想到必须有办法以某种方式解决这个问题。 / p>

解决方案

  field_queryset = Test.objects.all()
表单中的表单:
form.fields ['test_field']。queryset = field_queryset

/ p>

I have a model with a number of foreign key fields, e.g. model Product with fields 'type', 'level', 'color', 'intensity' (just a generic example).

I then have a page to edit all products of a given type using a Type form with the products as an inline formset with the option to add additional products inline using extra=10.

The thing i find very strange is that each time when i output one of the foreign key choice fields on the template Django queries the database for the get the options (every time).

For example:

{% for form in formset %}
    {{ form.level }}
    {{ form.color }}
    {{ form.intensity }}
{% endfor %}

With 20 products (and 10 empty extra forms) the above code issues 30 select * from ... from level, color and intensity totaling 90 queries (revealed using the Django Debug Toolbar), where 3 should be sufficient. The options are unlikely to change mid request, but even if they did I definitely wouldn't want some newly added options to appear in the last 5 forms only.

Is there any way to optimize my models/forms/views/templates so that the database doesn't get hammered like this unnecessarily?

-

Disclaimer: I'm relatively new to django and python and can't help thinking there must be a way to address this built in somehow.

解决方案

field_queryset = Test.objects.all()    
for form in formset:
        form.fields['test_field'].queryset = field_queryset

Like this.

这篇关于Django内联表单和选项字段会生成太多的数据库查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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