#35810: Provide `Select` class for `select_related` (like `Prefetch` exists for
`prefetch_related`)
-------------------------------------+-------------------------------------
     Reporter:  Bart van Andel       |                    Owner:  (none)
         Type:  New feature          |                   Status:  closed
    Component:  Database layer       |                  Version:  5.1
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:  wontfix
     Keywords:  query optimization   |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Changes (by Simon Charette):

 * resolution:   => wontfix
 * status:  new => closed

Comment:

 I'm struggling to find it now but I know the idea of allow custom classes
 to be provided to `select_related` was already discussed somewhere in the
 past years.

 I think the question here is less about whether we'd want to support such
 pattern but how exactly it should be achieved.

 For example, for reverse relationships it could be done using `LEFT JOIN
 LATERAL` on backends that support it

 {{{#!python
 chats = Chat.objects.select_related(
     Select(
         "messages",
         queryset=Message.objects.order_by("created_at"),
         to_attr="lastest_message",
     ),
 )
 }}}

 {{{#!sql
 SELECT
     chat.*,
     latest_message.*
 LEFT JOIN LATERAL (
     SELECT *
     FROM message
     WHERE chat_id = chat.id
     ORDER BY created_at DESC
     LIMIT 1
 ) latest_message
 }}}

 I'm not sure what the best way to express this through the ORM should be
 though. It feels like it could also be something that is expressed through
 a `Subquery` that doesn't make use of `values` to limit to a single field

 {{{#!python
 chats = Chat.objects.annotate(
     lastest_message=Message.objects.filter(
        chat_id=OuterRef("id"),
    ).order_by("created_at")[1]
 )
 }}}

 In all cases, just like any new large feature request,
 [https://docs.djangoproject.com/en/stable/internals/contributing/bugs-and-
 features/#requesting-features it should be discussed on the forum] before
 hand to gather consensus.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35810#comment:2>
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/01070192549cb080-036357de-d760-47a6-8ec1-1545d67c67a3-000000%40eu-central-1.amazonses.com.

Reply via email to