【问题标题】:Django duplicate database queriesDjango重复数据库查询
【发布时间】:2019-11-03 14:57:25
【问题描述】:

我正在使用django_debug_toolbar 来分析网页的性能。结果让我感到困惑的是数据库查询。无论我做了所有应该做的事情(我想),结果选项卡仍然显示重复的数据库查询警告。为了说明这个问题,我将 django 项目设置为如下所示:

models.py

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published', auto_now_add=True)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

views.py

from django.shortcuts import render

from .models import Question, Choice


def index(request):
    return render(request, 'polls/index.html', {'questions': Question.objects.all()})

index.html

{% for question in questions %}
  <p>{{ question.question_text }}</p>
  <ul>
    {% for choice in question.choice_set.all %}
      <li>{{ choice.votes }} votes - {{ choice.choice_text }}</li>
    {% endfor %}
  </ul>
{% endfor %}

在上面的 html 文件和视图中,我加载了所有问题及其相关选项。为了测试,我分别为他们添加了 2 个问题和 2 个和 4 个选项(总共 6 个选项)。而django_debug_toolbar SQL 结果如下:

我应该怎么做才能避免这些重复的 SQL 查询?我认为这些重复的查询可能会对大型网站的性能产生严重影响。一般而言,避免这些问题的方法和最佳做法是什么?

【问题讨论】:

    标签: python django django-queryset django-debug-toolbar


    【解决方案1】:

    您应该.prefetch_related(..) [Django-doc] 相关的Choices。然后 Django 会做一个额外的查询来一次性获取Choices,并在 Python/Django 级别进行 JOIN。

    def index(request):
        return render(
            request,
            'polls/index.html',
            {'questions': Question.objects.prefetch_related('choice_set')}
        )

    【讨论】:

      猜你喜欢
      • 2014-09-23
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多