【问题标题】:Can Django display data from multiple tables (Models/Classes) on a single page?Django 可以在单个页面上显示来自多个表(模型/类)的数据吗?
【发布时间】:2020-10-24 12:19:17
【问题描述】:

这是基于 Django 教程 (https://docs.djangoproject.com/en/3.0/intro/tutorial01/) 构建的“投票”应用程序。

它本质上是一个问题模型和一个选择模型。 Choice 模型通过外键(名为“question”)链接到 Question。

完成本教程后,我想尝试为应用添加特定功能:

在单个 html 页面上,显示所有问题的列表,以及每个问题下方的相关选项。 (同时显示每个选项的投票数将是一个加分项,但此时不是必需的。)

Something like this would be an ideal page display.

现在,我可以在一个页面上显示所有问题(没有选择)

-或-

一个问题与页面上的所有相关选项。

我似乎无法在一个页面上显示所有问题及其选择。

以下内容基于我能找到的类似问题和回复以及 djangoproject.com 文档。

models.py:

import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text

    <...etc: additional code here about pub_date...>
    
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

为了使用我想要的实例填充查询集,我尝试了基于类的视图(& 变体)和基于函数的视图(& 变体)。 (我对基于类的尝试最没有信心。如果有人想看,我会发布它。)

基于函数的视图方法:

view.py:

def func_allreslt(request):
    context = {}
    context["question"] = Question.objects.all()
    context["choice"] = Choice.objects.all()

    return render(request, "polls/funcallreslt.html", context)

funcallreslt.html:

<ul>
  {% for question in context %}
  <li> {{question.question_text }} </li>
  <ol type=1>
    {% for choice in context %}
    <li>{{ choice.choice_text }}</li>
    {% endfor %}
  </ol>
  {% endfor %}
</ul>

我也尝试过使用 prefetch_related 和/或 select_related 的各种组合。如果有人感兴趣,我可以提供该代码。

(我仍在使用 .all() 而不进行任何过滤或切片,因为数据库当前包含 4 个问题和大约 13 个选项,所以我认为没有必要减少正在检索的内容。)

谁能指出我正确的方向来完成这个?

(在此之后,我想我可能会经历并构建一系列 if/then 语句,看看我是否可以通过该逻辑列出结果。

我想到的另一条路是将它写成一个 SQL 查询,然后看看我是否可以让 Django 使用结果。)

【问题讨论】:

    标签: python html django


    【解决方案1】:

    无需将Choices 添加到上下文中。添加Question 查询集并在模板中呈现关联的Choices

    def func_allreslt(request):
        context = {}
        context["questions"] = Question.objects.all()
        return render(request, "polls/funcallreslt.html", context)

    在你的模板里面:

    <ul>
      {% for question in questions %}
      <li> {{question.question_text }} </li>
      <ol type=1>
        {% for choice in question.choice_set.all %}
        <li>{{ choice.choice_text }}</li>
        {% endfor %}
      </ol>
      {% endfor %}
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      相关资源
      最近更新 更多