Search code examples
pythondjangodjango-modelsdjango-database

How to apply select_related to the objects of a m2m relationship in Django?


Lets say there is a structure like this:

class Aaaaa(models.Model):
    b = models.ManyToManyField('Bbbbb')

class Bbbbb(models.Model):
    c = models.ForeignKey('Ccccc')

class Ccccc(models.Model):
    x = models.CharField(max_lenght="3")

Now I'm in the DetailView of Aaaaa. I do prefetch_related('b'). But how can I let Django know to get all the "Ccccc" as well?


Solution

  • You can work with a Prefetch object [Django-doc]:

    from django.db.models import Prefetch
    
    Aaaaa.objects.prefetch_related(
        Prefetch('b', Bbbbb.objects.select_related('c'))
    )