我正在关注民意调查应用程序的 Django 官方站点教程,完成后我正在进行一些改进以获取有关 Django 的更多知识。
我的第一个目的是更改 View 以显示所有问题及其可能的答案。
模型是:
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 个问题相关。
在 View 中,我能够呈现所有的问题、所有的选择,但不能呈现一个问题和他的选择。为此,我尝试了以下方法:
查看:
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')
html:
{% 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>
我试图找到一种方法来获取question_choice_list
上的不同的question_text
,但没有办法。我想尝试使用两个查询,1 来获取所有问题。然后在渲染问题时查询该问题 id 的 coices。但在尝试任何可以教给我一些不好的做法之前,我想知道如何用最佳实践来解决这个问题以及为什么要这样做。
我的方法离解决方案还很远吗?
最佳答案
要获取问题的所有相关选项,您需要执行以下操作:
questions = Question.objects.prefetch_related('choice_set').all()
您也不应该这样做:
Choice.objects.prefetch_related('question').all()
相反,你应该这样做:
Choice.objects.select_related('question').all()
参见Django Documentation对于 select_lated
和 prefetch_lated
关于python - Django prefetch_与FK相关到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50708398/