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?
You can obtain all the Profile
s related to one or more registers
with:
Profile.objects.filter(register__in=registers)
or you can obtain the Profile
s 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 Profile
s 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()