pythondjangodjango-modelsm2m

Many-to-Many relationship in Django


I have the following 3 models:

class Platform(models.Model):
    title = models.CharField(max_length=100, unique=True)

class Profile(models.Model):
    title = models.CharField(max_length=110, unique=True)
    platform = models.ManyToManyField(Platform)

class Register(models.Model):
    ...
    profile = models.ManyToManyField(Profile)
    ...

My views.py

def info(request):
    ...
    registers=Register.objects.all()
    ...
    for register in registers:
        profile= register.profile....???

I need to know the profile or profiles from a query of the Register model

is possible?


Solution

  • You can obtain all the Profiles related to one or more registers with:

    Profile.objects.filter(register__in=registers)

    or you can obtain the Profiles of a Register object:

    def info(request):
        # …
        registers=Register.objects.all()
        # …
        for register in registers:
            profiles = register.profile.all()

    but here you will hit the database per register, which might not scale very well.

    You can, like @IainShelvington says, use .prefetch_related(…) [Django-doc] to fetch all these related Profiles in memory with one extra query and do the JOIN at the Django/Python level:

    def info(request):
        # …
        registers=Register.objects.prefetch_related('profile')
        # …
        for register in registers:
            profiles = register.profile.all()