Opened 10 years ago
Last modified 8 years ago
#24975 closed New feature
Prefetch_related from object directly — at Initial Version
Description ¶
The current prefetch_related works with a queryset, so if I have, in an ecommerce site, an order with articles, I can do orders = Order.objects.prefetch_related("articles")
.
If I do now orders[0].articles.all()
, it will not query the database again.
Suppose I have an "order" and I want to prefetch the articles (I will need them several times later). If I want to prefetch them, afaik, I would need to store them in a variable in order to reuse the same articles, since every time I do order.articles.all()
it queries the db again as expected.
It's a bit inconvenient (and maybe illogical) that I can prefetch objects from a queryset (a "list" of objects), but not from the object itself.
I worked around this issue, by doing the following:
`
articles = order.articles.all()
order._prefetched_objects_cache = {"articles": articles}
`
I propose to have somethins like order.prefetch("articles") that would do exactly what I did (but of course take care of verifying if _prefetched_objects_cache
already exists and any other precautions needed.