【发布时间】: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