Django: implementing JOIN using Django ORM?
Consider using models.ForeignKey(Question)
instead of question_id = IntegerField()
.
This is the optimal (more relational) way to express the relationship between Questions and Answers you are trying to portray.
This way you can simply call Answers.objects.filter(question_id=<id>)
and get exactly what you're looking for.
class Question(models.Model):
title = models.CharField(max_length=70)
details = models.TextField()
class Answer(models.Model):
question = models.ForeignKey('Question')
details = models.TextField()
id = <whatever_id>
answers = Question.objects.get(id=id).answer_set.all()
This is exactly what select_related() does. The only gotcha is that you have to start with the Answer model, rather than Question, but the result is the same:
answers = Answer.objects.filter(question_id=1).select_related()
Now each answer object has a pre-fetched 'question' attribute, and accessing it won't hit the db again.