如何在LearnerQuestionAnswer模型上过滤查询集?

时间:2018-05-26 05:15:15

标签: python django django-models

我有一个名为测验的模型。每个测验在模型Quiz_Question中都有一组相关的问题。

测验模型: -

class Quiz(models.Model):
    quiz_name = models.CharField(max_length=200)

Quiz_Question模型: -

class Quiz_Question(models.Model):
    quiz = models.ForeignKey(Quiz, related_name='questions')
    text = models.CharField(max_length=200)

现在,我可以使用related_name属性获取特定测验的所有问题,如下所示: -

all_quizes = Quiz.objects.all()

一个特别的测验: -

quiz = all_quizes[0]

与此测验相关的所有问题如下: -

all_related_questions = quiz.questions.all()

我有另一个模型作为LearnerQuestionAnswer,其中学习者是普通的django用户: -

class LearnerQuestionAnswer(models.Model):
    quiz_question = models.ForeignKey(Quiz_Question)
    learner = models.ForeignKey(User)

我可以在Quiz_Question模型中过滤掉测验和学习者特定的问题,如下所示: -

quiz = all_quizes[0]
learner= User.objects.get(id=1)
Quiz_Question.objects.filter(quiz=quiz, learnerquestionanswer__learner=learner)

如何在LearnerQuestionAnswer模型上进行类似过滤,以便我可以像上面那样获得测验和学习者特定的查询集?

1 个答案:

答案 0 :(得分:0)

您可以使用quiz_question__quiz查找按quize过滤。使用以下查询按测验和学习者进行查询:

quiz = all_quizes[0]
learner= User.objects.get(id=1)
LearnerQuestionAnswer.objects.filter(quiz_question__quiz=quiz, learner=learner)

按相关模型的字段检查有关过滤器的文档的this part