gpt4 book ai didi

python - Django重复数据库查询

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:02 25 4
gpt4 key购买 nike

我正在使用 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 结果如下:

enter image description here

enter image description here

我应该怎么做才能避免这些重复的 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>}
)

关于python - Django重复数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58681373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com