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.
I have not read all of Django documentation.
I do not know if it is expected that most developers would read everything.
Hence, I learn using Google top ranked pages inside Django
documentation when I search for a narrow topic on Django.
If I search
django prefetch
django prefetching
django prefetch_related
django prefetch_related_objets
I have https://docs.djangoproject.com/fr/4.0/ref/models/querysets/ as
first result but your link does not appear.
If I search
django cache
django caching
I get this
https://docs.djangoproject.com/fr/4.0/topics/cache/ but also your link as the third answer of Google.
Maybe, adding a link to /topics/db/optimization from
ref/models/querysets/ would help Google and people like me find this
information more easily :)