在Django中使用多个外键进行过滤

时间:2019-07-12 18:33:53

标签: django django-models django-queryset

因此,我已经存储了一个考试,并且能够过滤出仅来自该考试的问题,但是,我怎么只打印出他们指定问题的答案呢?

当我尝试将其打印在模板中时,所有答案选项均会打印在每个问题下而不是过滤掉,我是否需要模板中的for循环/ if语句来正确执行此操作?我已经尝试了很多方法,文档很可能会给出答案,但我只需要帮助即可理解

from django.db import models


class Exam(models.Model):

    name = models.CharField(max_length=64, verbose_name=u'Exam name', )
    slug = models.SlugField()

    def __str__(self):
        return self.name


class Question(models.Model):
    question_text = models.CharField(max_length=256, verbose_name=u'Question\'s text')
    is_published = models.BooleanField(default=False)
    exam = models.ForeignKey(Exam, related_name='questions')

    def __str__(self):
        return "{content} - {published}".format(content=self.question_text, published=self.is_published)


class Answer(models.Model):

    text = models.CharField(max_length=128, verbose_name=u'Answer\'s text')
    is_valid = models.BooleanField(default=False)
    question = models.ForeignKey(Question, related_name='answers')

    def __str__(self):
        return self.text

视图

def detail(request, exam_id):
    exam = Exam.objects.get(id = exam_id)
    question = exam.question_set.all()
    answer = Answer.objects.filter(question__exam=exam)


    template = loader.get_template('exam/start_exam.html')
    context = {
        'exam': exam,
        'question': question,
        'answer': answer,
    }
    return HttpResponse(template.render(context))

我如何能够在模板上打印考试,并对其进行过滤以打印问题,以及从外键打印与之相关的答案

1 个答案:

答案 0 :(得分:0)

您认为:

def detail(request, exam_id):
    exam = Exam.objects.get(id=exam_id)
    questions = exam.questions.prefetch_related('answers').all()
    template = loader.get_template('exam/start_exam.html')
    context = {
        'exam': exam,
        'questions': questions,
    }
    return HttpResponse(template.render(context))

在您的模板中:

<h2> Exam {{exam.name}} </h2>
{% for question in questions %}
    <h3>Question: {{ question.text }}</h3>
    <h4>Answers:</h4>
    <ul>
    {% for answer in question.answers.all() %}
        <li> {{ answer.text }} </li>
    {% endfor %}
    </ul>
{% endfor %}