Opened 9 years ago

Last modified 8 years ago

#24975 closed New feature

Prefetch_related from object directly — at Initial Version

Reported by: Eduardo Klein Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

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.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top