I have a model named Quiz. Each Quiz has a set of related questions in the model Quiz_Question.
Quiz Model:-
class Quiz(models.Model):
quiz_name = models.CharField(max_length=200)
Quiz_Question Model:-
class Quiz_Question(models.Model):
quiz = models.ForeignKey(Quiz, related_name='questions')
text = models.CharField(max_length=200)
Now I can get all the questions for a particular quiz using the related_name attribute as follows:-
all_quizes = Quiz.objects.all()
A particular quiz:-
quiz = all_quizes[0]
All the questions related to this quiz as follows:-
all_related_questions = quiz.questions.all()
I have another model as a LearnerQuestionAnswer where learner is a normal django user:-
class LearnerQuestionAnswer(models.Model):
quiz_question = models.ForeignKey(Quiz_Question)
learner = models.ForeignKey(User)
I can filter out the quiz and learner specific questions on the Quiz_Question Model like this:-
quiz = all_quizes[0]
learner= User.objects.get(id=1)
Quiz_Question.objects.filter(quiz=quiz, learnerquestionanswer__learner=learner)
How can I filter out similarly on the LearnerQuestionAnswer Model so that I can get quiz and learner specific queryset just like the above one?
You can use quiz_question__quiz
lookup to filter by quize. Use following query to query by quiz and learner:
quiz = all_quizes[0]
learner= User.objects.get(id=1)
LearnerQuestionAnswer.objects.filter(quiz_question__quiz=quiz, learner=learner)
Check this part of the doc about filter by related model's fields.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.