我正在使用 Django 构建一个类似调查的应用程序。我有 3 个模型(调查、问题、答案)。我需要查询问题模型并拉回问题加上每个问题的可能答案。然后,我需要将其作为单个问题显示在 html 页面上,并在列表或其他元素中显示可能的答案。Django==2.2.1 / Pillow==6.1.0/ pytz==2019.1/ sqlparse==0.3.0/ Python 3.7 我尝试从 Answers 模型开始,但我最终得到重复的数据并且不确定如何呈现。模型.PYclass 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_askclass 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意见.PYdef 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...
2 回答
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
这应该有效。
your_question_object.answer = your_question_object.answer_set.all()
这应该添加您问题的所有可能答案,这些答案将外键作为您的问题来answer
归因于your_question_object
qq_笑_17
TA贡献1818条经验 获得超7个赞
我认为 {% endfor %} 的问题
<body>
<div class=questions>
{% if questions %}
<h1> {% for q in questions %}</h1>
<p> {{ q.question_to_ask }}</p>
{% endfor %}
<p> {% for a in answers %}</p>
<p> {{ a.question.question_to_ask }}</p>
{% endfor %}
{% else %}
<p> NO RECORDS SHOWN</p>
{% endif %}
</div>
添加回答
举报
0/150
提交
取消