Skip to main content
 首页 » 编程设计

python之Django重复数据库查询

2024年08月12日49wayfarer

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

模型.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 文件和 View 中,我加载了所有问题及其相关选项。为了测试,我只添加了2个问题,分别为它们添加了2个和4个选项(总共6个选项)。 django_debug_toolbar SQL 结果如下:

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

请您参考如下方法:

你应该.prefetch_related(..) [Django-doc]相关的 Choice。然后 Django 将进行额外的查询以一次获取所有 Choice,并在 Python/Django 级别执行 JOIN。

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