Django Prefetch Through Table
I have a Django model which has a manyToMany relation with an additional column: class Field(models.Model): table = models.ForeignKey( Table, on_delete=models.CASCADE,
Solution 1:
It wasn't really what I was lookig for but it helped me to build my query:
table = Table.objects.get(pk=1)
fields = table.fields.prefetch_related("fieldslanguages_set", "fieldslanguages_set__language").order_by("position")
for field in fields:
for fl in field.fieldslanguages_set.all():
print(fl.defaultValue, fl.language)
The problem with Kevin Christopher Henry's answer is that it will query the database for each field in the for-loop. Here it will send only 4 queries.
Solution 2:
The through table is a table like any other, which means you can reference it through the related names of its ForeignKeys
.
table = Table.objects.get(pk=1)
fields = table.fields.prefetch_related("fieldslanguages__language")
.order_by("position"))
for field in fields:
for fl in field.fieldslanguages_set.all():
print(fl.default, fl.language)
Post a Comment for "Django Prefetch Through Table"