[Answered ]-Django โ€“ Best practice to join two models

2๐Ÿ‘

โœ…

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)

๐Ÿ‘คYardenST

Leave a comment