get foreign key objects in a single query - Django

后端 未结 3 707
感动是毒
感动是毒 2021-01-02 02:11

I have 2 models in my django code:

class ModelA(models.Model):
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=255)         


        
3条回答
  •  走了就别回头了
    2021-01-02 02:58

    As Ofri says, select_related only works on forwards relations, not reverse ones.

    There's no built-in way to automatically follow reverse relations in Django, but see my blog post for a technique to do it reasonably efficiently. The basic idea is to get all the related objects for every item at once, then associate them manually with their related item - so you can do it in 2 queries rather than n+1.

提交回复
热议问题