Django与FK一起prefetch_related到一个视图中



我正在遵循 Django 官方网站的民意调查应用程序教程,完成后,我正在努力进行一些改进,以获取有关 Django 的更多知识。

我的第一个目的是更改视图以显示所有问题和可能的答案。

这些模型是:

class Question(models.Model):
question_text = models.CharField(max_length=200)
publication_date=models.DateTimeField()
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.publication_date <= now
was_published_recently.admin_order_field = 'publication_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question=models.ForeignKey(Question,on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text

如您所见,1 个选择与 1 个问题相关。

在这种观点中,我能够呈现所有的问题,所有的选择,但不是问题和他的选择。为此,我尝试了以下方法:

查看

from django.http import HttpResponse,HttpResponseRedirect
from .models import Choice,Question
from django.shortcuts import get_object_or_404,render
from django.urls import reverse
from django.views import generic
from django.utils import timezone
class IndexView(generic.ListView):
template_name = 'surveys/index.html'
context_object_name = 'question_choice_list'
def get_queryset(self):
return Choice.objects.all().prefetch_related('question')

目录

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'surveys/style.css' %}" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if question_choice_list %}
<ul>
{% for question_choice_pair in question_choice_list %}
<li><a href="{% url 'surveys:detail' question_choice_pair.question.id %}">{{ question_choice_pair.question.distinct.question_text }}</a></li>
{% if question_choice_pair %}
<ul>
{% for choice in question_choice_list %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No answers are available.</p>
{% endif %}
{% endfor %}
</ul>
{% else %}
<p>No questions are available.</p>
{% endif %}
</body>
</html>

我试图找到一种方法来获得distinct question_textquestion_choice_list但没有办法。我想尝试两个查询,1 个以获得所有问题。然后在渲染问题时查询该问题 id。但在尝试任何可以教我一些不良做法的东西之前,我想知道如何用最好的做法来解决这个问题,以及为什么要这样做。

¿这是我的解决方案吗?

要获取问题的所有相关选项,您需要执行以下操作:

questions = Question.objects.prefetch_related('choice_set').all()

你也不应该这样做:

Choice.objects.prefetch_related('question').all()

相反,您应该这样做:

Choice.objects.select_related('question').all()

请参阅 Django 文档以获取select_relatedprefetch_related

最新更新