Django: implementing JOIN using Django ORM?

前端 未结 4 939
误落风尘
误落风尘 2020-12-01 12:43

I have a Q&A type of site built in Django with the following models:

class Question(models.Model):
    title = models.CharField(max_length=70)
    detail         


        
4条回答
  •  执念已碎
    2020-12-01 13:13

    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.

提交回复
热议问题