#26565: Allow Prefetch query to use .values()
-------------------------------------+-------------------------------------
     Reporter:  Maxime Lorant        |                    Owner:  nobody
         Type:  New feature          |                   Status:  new
    Component:  Database layer       |                  Version:  dev
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:  prefetch, values     |             Triage Stage:  Accepted
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by Simon Charette):

 > What's the workaround for this if I have a similar need?

 Perform the prefetch queryset and attribute assignment yourself. In the
 end `prefetch_related` only does the following

 It transforms

 {{{#!python
 Authors.objects.filter(popular=True).prefetch_related(Prefetch("books",
 to_attr="prefetched_books"))
 }}}

 Into

 {{{#!python
 authors = Authors.objects.filter(popular=True)
 authors_books = defaultdict(list)
 for book in Book.objects.filter(author__in=authors):
     authors_books[book.author_id].append(book)
 for author in authors:
     setattr(author, "prefetched_books", authors_books[author.pk])
 }}}

 So as long as the back references is included in your `values` (which is
 something the `prefetch_related` code would need to do anyway and the part
 Micah ran into issues with) you should be able to achieve the same thing
 with two loops.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/26565#comment:18>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/01070182cb9d387a-8deced05-ff7a-4c26-b22c-c9422d643d7e-000000%40eu-central-1.amazonses.com.

Reply via email to