python - Django prefetch_与FK相关到 View 中

标签 python html django

我正在关注民意调查应用程序的 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_latedprefetch_lated

关于python - Django prefetch_与FK相关到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50708398/

相关文章:

python - 通过限制字节读取网站的部分内容

python - 谷歌 API 服务帐户。即使使用域范围委派访问也只能看到服务帐户驱动器

html - 黑色的左/右指向三角形大小不一样

python - Django Rest Framework,我可以使用 ViewSet 从 Django View 函数生成 json 吗?

python - 请求/响应中间件中的 Django 错误 - TypeError : __init__() takes 1 positional argument but 2 were given

python - 我可以只使用 PYC 文件吗

html - 具有重叠元素的固定大小行

javascript - 模拟目录File对象

django - 在 Django Rest Framework 中过滤详细结果

python - 如何使用数据类型(datetime,float)制作一个 numpy recarray?