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?

2

1 Answer 1

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.

1
  • I actually do need the attributes directly. Thanks for correcting me on the use of arrays though. Nov 28, 2012 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.