Django-有没有一种方法可以优化循环中的ORM ManyToOne调用?

时间:2019-02-07 22:40:27

标签: python django django-models django-views django-orm

我看到自己在Django视图中有这种模式:

<ol>
{% for a in ModelA %}
    <li>{{ a.title }}</li>
    <ol>
    {% for b in a.modelb_set.all %}
        <li>{{ b.title }}</li>
        <ul>
            {% for c in b.modelc_set.all %}
                <li>{{ c.text }}</li>
                <ul>
                {% for d in c.modeld_set.all %}
                    <li>{{ d.text }}</li>
                {% endfor %}
                </ul>
            {% endfor %}
        {% endif %}
        </ul>
    {% endfor %}
    </ol>
{% endfor %}
</ol>

当然,这里的问题是这正在进行n ^ 4个数据库调用,这是非常不可扩展的。对于单个ModelA对象,我要进行大约23个SQL查询,并且我认为这个数字只会随着ModelA查询数量的增加而增加。

是否有一般的方法可以减少此处需要进行的查询数量?任何想法将不胜感激:)

(如果您感到好奇,实际的代码是here-ModelA是Poll,ModelB是TextChoiceQuestion,ModelC是TextChoice,而ModelD是TextChoiceNuance。

1 个答案:

答案 0 :(得分:3)

您有模特吗? 如果是这样,我建议上传模型代码。

我通常这样编码。 首先,如果我使用ManyToManyField,请使用prefetch_related('fields','field__subfield',)。

Model.objects.prefetch_related('afield', 'afield__bmodel_field', 'afield__bmodel_field__cmodel_field')

第二,您必须使用related_name。不管ManyToManyField,ForeignKey,您都可以获得更好的相关名称。

class CheckList(models.Model):
    """docstring for CheckList"""
    """ 설명 """
    name = models.CharField(max_length=30)

   def __str__(self):
       return self.name

class Question(models.Model):
    checklist = models.ForeignKey(CheckList, 
            on_delete=models.CASCADE, related_name='questions')

# example
check_list = CheckList.objects.prefetch_related('questions').all()