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')
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…