python - Django prefetch_related from foreignkey with manytomanyfield not working -
for example, in django 1.8:
class a(models.model): x = models.booleanfield(default=true) class b(models.model): y = models.manytomanyfield(a) class c(models.model): z = models.foreignkey(a)
in scenario, c.objects.all().prefetch_related('z__b_set')
doesn't work.
is there way prefetch information need c[0].z.b_set.all()
work without query?
you can use select_related
follow first part of relationship (c.z
's foreignkey
) in 1 batch:
c.objects.all().select_related('z').prefetch_related('z__b_set')
the prefetch_related
part, however, done in @ least 2 queries, stated in docs:
prefetch_related, on other hand, separate lookup each relationship, , ‘joining’ in python. allows prefetch many-to-many , many-to-one objects, cannot done using select_related, in addition foreign key , one-to-one relationships supported select_related. supports prefetching of genericrelation , genericforeignkey.
Comments
Post a Comment