2

Carrying on from this example, I would like to perform a reverse query like this:

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

I would expect this to return an array of arrays. Inside each individual array, the reverse lookup going back to pizza should itself be an array.

result = ['name':'Pineapple', 'pizza_set':[{'name':'Hawaiian'... ... }]]

As is, my query does not follow back through the pizza_set. Any ideas what I'm doing wrong?

snakesNbronies
  • 3,619
  • 9
  • 44
  • 73
  • Do you need to define a related_name on the model? http://stackoverflow.com/questions/9176430/django-does-prefetch-related-follow-reverse-relationship-lookup – Enrico Nov 28 '12 at 09:28
  • That's similar to what I want, but I'd like the query to return the values from the 'prices' instance – snakesNbronies Nov 28 '12 at 18:58

1 Answers1

1

Firstly, there are no "arrays" (in Python we call those "lists", but never mind) here. The result of a call to all() is a QuerySet, which is a list-like container - and the things it contains are not lists either, but objects of the relevant kind - in this case, Topping instances. Each instance is filled from the database, and the point of using prefetch_related - as explained in your link - is that it populates an internal cache on each for those instances which is then used when you call the related set. You don't need to access that attribute directly but when you call obj.pizza_set.all() on any of the items in your Topping queryset it will be used, which you can verify by checking the database hits.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895