Django prefetch_related From Model With Multiple ManyToMany Relationships
Question:
Say I have a few models in Django:
class Foo(models.Model):
bars = models.ManyToManyField(Bar)
bazs = models.ManyToManyField(Baz)
class Bar(models.Model):
quxs = models.ManyToManyField(Qux)
I can use prefetch_related to get all Bars belonging to Foo and all Quxs belonging to Bar with:
Foo.objects.prefetch_related('bars__quxs')
But how can I use prefetch_related to get this information as well as all the Bazs belonging to Foo? Would something like:
Foo.objects.prefetch_related('bars__quxs', 'bazs')
work?
Answers:
Yes. You can pass in multiple lookups to .prefetch_related()
Say I have a few models in Django:
class Foo(models.Model):
bars = models.ManyToManyField(Bar)
bazs = models.ManyToManyField(Baz)
class Bar(models.Model):
quxs = models.ManyToManyField(Qux)
I can use prefetch_related to get all Bars belonging to Foo and all Quxs belonging to Bar with:
Foo.objects.prefetch_related('bars__quxs')
But how can I use prefetch_related to get this information as well as all the Bazs belonging to Foo? Would something like:
Foo.objects.prefetch_related('bars__quxs', 'bazs')
work?
Yes. You can pass in multiple lookups to .prefetch_related()