我正在使用 Django 构建一个类似调查的应用程序。我有 3 个模型(调查、问题、答案)。我需要查询问题模型并拉回问题加上每个问题的可能答案。然后,我需要将其作为单个问题显示在 html 页面上,并在列表或其他元素中显示可能的答案。
Django==2.2.1 / Pillow==6.1.0/ pytz==2019.1/ sqlparse==0.3.0/ Python 3.7 我尝试从 Answers 模型开始,但我最终得到重复的数据并且不确定如何呈现。
模型.PY
class Question(models.Model):
survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
question_sequence = models.IntegerField()
question_to_ask = models.CharField(max_length=4000, unique=True)
def __str__(self):
return self.question_to_ask
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
possibleAnswer = models.CharField(max_length=4000)
possibleAnswer_image = models.ImageField(blank=True, null=True)
def __str__(self):
return self.possibleAnswer
意见.PY
def survey(request):
q = [x for x in Question.objects.all().values()]
questions_dict = {'questions': q}
# a = [x for x in Answer.objects.select_related().all()]
# answers_dict = {'answers': a}
return render(request, 'survey_app/survey.html', context=questions_dict)
.HTML
<body>
<div class=questions>
{% if questions %}
<h1> {% for q in questions %}</h1>
<p> {{ q.question_to_ask }}</p>
<p> {% for a in answers %}</p>
<p> {{ a.question.question_to_ask }}</p>
{% endfor %}
{% endfor %}
{% else %}
<p> NO RECORDS SHOWN</p>
{% endif %}
</div>
</body>
我的目标是在 html 上显示:
Question_To_Ask (q1)
PossibleAnswer / possibleAnswer_image(用于 q1)
PossibleAnswer / possibleAnswer_image(用于 q1)
Question_To_Ask (q2)
PossibleAnswer / possibleAnswer_image(对于 q2)
PossibleAnswer / possibleAnswer_image(对于 q2)
PossibleAnswer / possibleAnswer_image(对于 q2)
PossibleAnswer / possibleAnswer_image(对于 q2)
ETC...
qq_花开花谢_0
qq_笑_17
相关分类