Hello,

I made a simple test to check the number of queries done :

# First part
order = Order.objects.get(id=22222)  # one query
items = list(order.items.all())  # one query
items = list(order.items.all())  # one query
items = list(order.items.all())  # one query

# Second part
order = Order.objects.prefetch_related("items").get(id=22222)  # two queries
items = list(order.items.all())  # no query
items = list(order.items.all())  # no query
items = list(order.items.all())  # no query

# Third part
order = Order.objects.get(id=22222)  # one query
prefetch_related_objects([order], "items")  # one query
items = list(order.items.all())  # no query
items = list(order.items.all())  # no query
items = list(order.items.all())  # no query
prefetch_related_objects([order], "items")  # no more query
prefetch_related_objects([order], "items")  # no more query

I was surprised that there was 4 queries for the First part of the test 
instead of 2 for the other parts, because I was expecting that .all() would 
also fill the cache and not only use it.
Maybe it is intended.
I think that this test or something else explaining this point could 
enhance the documentation on prefetch_related() and 
prefetch_related_objects().
I advised my colleagues to use prefetch_related_objects() when in doubt 
whether the objects given have been already extended with prefetching.

Best regards,
     Laurent Lyaudet




-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/806fd09c-b997-4a1d-91c0-9c4cf5860f2an%40googlegroups.com.

Reply via email to