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

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -