猿问

Django 模型 - 如何从 2 个模型中提取数据并渲染

我正在使用 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...


繁星点点滴滴
浏览 126回答 2
2回答

qq_花开花谢_0

这应该有效。your_question_object.answer&nbsp;=&nbsp;your_question_object.answer_set.all()这应该添加您问题的所有可能答案,这些答案将外键作为您的问题来answer归因于your_question_object

qq_笑_17

我认为 {% endfor %} 的问题<body>&nbsp; <div class=questions>&nbsp; &nbsp; {% if questions %}&nbsp; <h1> {% for q in questions %}</h1>&nbsp; &nbsp; <p> {{ q.question_to_ask }}</p>&nbsp; &nbsp; &nbsp; &nbsp; {% endfor %}&nbsp; &nbsp; &nbsp; <p> {% for a in answers %}</p>&nbsp; &nbsp; &nbsp; <p> {{ a.question.question_to_ask }}</p>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {% endfor %}&nbsp; &nbsp; {% else %}&nbsp; &nbsp; &nbsp; <p> NO RECORDS SHOWN</p>&nbsp; &nbsp; {% endif %}&nbsp; </div>
随时随地看视频慕课网APP

相关分类

Python
我要回答