I'm developing a project that allows users to make a test based in some random questions. My models.py has this two classes:
class Question(models.Model):
content = models.CharField()
...
class Answer(models.Model):
content = models.CharField()
isCorrect = models.BooleanField()
question = models.ForeignKey(Question)
And in my views.py I get 20 random questions using this query:
questions = Question.objects.order_by('?')[:20]
With this approach I have only the questions but I want also the answers related to every question, I found some solutions but I'd like to know what could be the best practice to get Question and related Answers? Can I add them to Question constructor?
Thanks!
You can do as @karthikr said, but it will make an extra database call for each question.
I would do it maybe this way:
questions = Question.objects.order_by('?')[:20]
answers = Answer.objects.filter(question__in=questions)
#some databases will not suppoert this, so use:
#answers = Answer.objects.filter(question_id__in=[q.id for q in questions])
for question in question:
answers_for_question = filter(lambda answer:answer.question_id = question_id, answers)
Which is only 2 db calls instead of 21
(For a really large sets of questions, make use of itertools to get the answers. for even better performance)