Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django prefetch_related with reverse foreign key lookup

Given these models in the Django docs:

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 want to get toppings and do stuff with their pizza_set:

toppings = Topping.objects.all()

for topping in toppings:
   pizzas_with_this_topping = topping.pizza_set()
   # do stuff with pizzas_with_this_topping

How can I use prefetch_related (or another technique) to get all the pizza data without hitting the database for every Pizza in every Topping?

like image 450
43Tesseracts Avatar asked May 05 '18 20:05

43Tesseracts


1 Answers

prefetch them like this:

toppings = Topping.objects.prefetch_related('pizza_set')

then the following won't hit the database:

for topping in toppings:
    pizzas_with_toppings = topping.pizza_set.all()

I'd like to add that Django tries hard to be easy to use for simple things (and no doubt Django does it great), but this obviously makes Django to do a lot of implicit things, which are not immediatelly obvious from the apps' code, so when you do something advanced you should expect unexpected, read Django docs which clarify all the magic and use tools like Django Debug Toolbar etc to verify that everything works as you expect it to.

like image 102
Bob Avatar answered Nov 15 '22 04:11

Bob