Django prefetch_related with m2m through relationship

后端 未结 1 875
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 04:26

I have the following models

class Film(models.Model):
    crew = models.ManyToManyField(\'Person\', through=\'Role\', blank=True)

class Role(models.Model):
             


        
1条回答
  •  伪装坚强ぢ
    2021-02-06 04:46

    You can construct your queryset like this:

    from django.db.models import Prefetch
    
    def get_queryset(self):
        return super(FilmDetail, self).get_queryset().prefetch_related(
            Prefetch(
                'crew',
                queryset=Role.objects.select_related(
                    'person',
                    'person_role',
                ),
            ),
        )
    

    Only Film->Role is a backwards relation loadable with prefetch_related. Role->RoleType and Role->Person are forwards relations that you load with select_related.

    0 讨论(0)
提交回复
热议问题