How to prefetch_related in reverse of a Django ManyToMany field

懵懂的女人 提交于 2020-01-06 06:44:25

问题


In Django, if I have a ManyToManyField:

class Topping(models.Model):
    name = models.CharField(max_length=30)

class Pizza(models.Model):
    name = models.CharField(max_length=50)
    toppings = models.ManyToManyField(Topping)

I can minimize hits on the database when accessing the Pizza model's toppings field by using prefetch_related():

Pizza.objects.all().prefetch_related('toppings')

How can I do the same but in reverse, to prefetch the pizza_set from a Topping queryset?

This doesn't work, and I couldn't find it in the docs:

Topping.objects.all().prefetch_related('pizza_set')


回答1:


This should work if you access the prefetched pizzas like this:

topping.pizza_set.all()

If you do something like

topping.pizza_set.filter(...some conditions etc...)

then it won't work and this is expected (as only specific query result is prefetched).



来源:https://stackoverflow.com/questions/49844181/how-to-prefetch-related-in-reverse-of-a-django-manytomany-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!