python - Django - Best practice to join two models -
i'm developing project allows users make test based in random questions. models.py has 2 classes:
class question(models.model): content = models.charfield() ... class answer(models.model): content = models.charfield() iscorrect = models.booleanfield() question = models.foreignkey(question) and in views.py 20 random questions using query:
questions = question.objects.order_by('?')[:20] with approach have questions want answers related every question, found solutions i'd know best practice question , related answers? can add them question constructor?
thanks!
you can @karthikr said, make database call each question.
i maybe way:
questions = question.objects.order_by('?')[:20] answers = answer.objects.filter(question__in=questions) #some databases not suppoert this, use: #answers = answer.objects.filter(question_id__in=[q.id q in questions]) question in question: answers_for_question = filter(lambda answer:answer.question_id = question_id, answers) which 2 db calls instead of 21
(for large sets of questions, make use of itertools answers. better performance)
Comments
Post a Comment