Opened 9 years ago

Last modified 8 years ago

#24975 closed New feature

Prefetch_related from object directly — at Version 1

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 (last modified by Tim Graham)

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 (1)

comment:1 by Tim Graham, 9 years ago

Component: UncategorizedDatabase layer (models, ORM)
Description: modified (diff)
Version: 1.8master
Note: See TracTickets for help on using tickets.
Back to Top