I have an app that saves Student quizzes using two models:
StudentQuiz
saves the questions the student was asked
StudentQuestion
saves the responses of the student for each of those questions.
class StudentQuestion(models.Model):
user = models.ForeignKey(User)
question = models.ForeignKey('Question') # comes from a Questions table
answer = models.CharField("Answer", max_length = 100, blank=True, null=True)
q_score = models.IntegerField("Score", blank=True, null=True)
class StudentQuiz(models.Model):
user = models.ForeignKey(User)
date = models.DateField("Quiz Date", blank=True, null=True)
total_score = models.IntegerField("Score", blank=True, null=True)
ques1 = models.ForeignKey(StudentQuestion, related_name='q1')
ques2 = models.ForeignKey(StudentQuestion, related_name='q2')
ques3 = models.ForeignKey(StudentQuestion, related_name='q3')
ques4 = models.ForeignKey(StudentQuestion, related_name='q4')
ques5 = models.ForeignKey(StudentQuestion, related_name='q5')
I want to find the number of questions a student took in a certain date range for which he got a score of, say, 1.
So I create the first queryset:
quizzes_done = StudentQuiz(user=mystudent, date__gte=start_date, date__lte=end_date)
Now, I want to look at all questions that are in these StudentQuizzes
and want to count the number of questions that have q_score = 1
.
Currently, I am just looping over the QuerySet and doing this programmatically. But the QuerySet could be huge.
Is there a way to do this using django's DB APIs?
take a look at the docs on queries that span relationships
basically, you should just be able to reference the student_quiz
associated with your StudentQuestion
object in a query on StudentQestion
, filtering on q_score
and user, and then use __
to access the StudentQuiz
properties you want (e.g. filter(student_quiz__date_gte=blah
)