【问题标题】:Display multiple dynamic object with for loops in templates在模板中使用 for 循环显示多个动态对象
【发布时间】:2020-09-28 18:00:54
【问题描述】:

所以总结一下,我的数据库结构是这样的:

test
  |_ question
      |_ choice
      |_ choice
      |_ choice
  |_ question
      |_ choice
      |_ choice
      |_ choice

现在我想在一个页面上显示每个问题的所有选项。

我的views.py

def index(request):
    data = {
        'greeting': 'Welcome User!',
        'form_test': forms.TestForm,
        'form_question': forms.QuestionForm,
        'form_choice': forms.ChoiceForm,
        'test': models.Test.objects.get(pk=1),
        'questions': models.Question.objects.filter(test_id__exact=1),
    }

    questions = models.Question.objects.filter(test_id=1)

    for question in questions:
        data['choices_{}'.format(question.id)] = models.Choice.objects.filter(question_id=question.id)

    print(data)
    return render(request, 'et_app/index.html', context=data)

所以从技术上讲,如果我有 2 个问题,我的 data 看起来像这样:

{
...
'choices_1': ...
'choices_2': ...
...
}

现在,我的问题是在模板上显示这些choices。我试过了:

{% for question in questions %}
    <h4>Q: {{ question.content }}</h4>

    <p>Choices:</p>
    <ul class="list-group">
        {% for choice in 'choices_{}'.format(question.id) %}
            <li class="list-group-item">{{ choice.content }}</li>
        {% endfor %}
    </ul>
{% endfor %}

它只是破坏了整个事情。我对 Django 比较陌生,所以请原谅我的幼稚。我怎样才能解决这个问题?非常感谢!

更新

models.py:

# Create your models here.
def generate_code():
    return get_random_string(length=7)


class Test(models.Model):
    test_code = models.CharField(max_length=7, editable=False, unique=True, default=generate_code())
    name = models.CharField(max_length=100, default=None)

    def __str__(self):
        return self.name


class Question(models.Model):
    test = models.ForeignKey(Test)
    content = models.CharField(max_length=900)

    def __str__(self):
        return self.content


class Choice(models.Model):
    question = models.ForeignKey(Question)
    content = models.CharField(max_length=900)

    def __str__(self):
        return "{} - {}".format(self.content, self.question.content)

【问题讨论】:

  • 添加您的模型
  • @ArakkalAbu 更新了我的问题

标签: python django django-views django-templates


【解决方案1】:

您首先不需要手动构建选择上下文变量(data['choices_{}'.format(question.id)] 部分)。

你只需要在你的模板中做这样的事情:

{% for question in questions %}
    <h4>Q: {{ question.content }}</h4>

    <p>Choices:</p>
    <ul class="list-group">
        {% for choice in question.choice_set.all %}
            <li class="list-group-item">{{ choice.content }}</li>
        {% endfor %}
    </ul>
{% endfor %}

关键部分是question.choice_set.all; Django 自动构建反向关系访问器。请参阅文档:Making queries: Related objects

【讨论】:

  • 非常感谢! :)
猜你喜欢
  • 2018-08-11
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 2022-12-05
  • 2019-03-13
  • 1970-01-01
相关资源
最近更新 更多