#29527: Multi-column comparisons
--------------------------------+--------------------------------------
     Reporter:  Ryan Hiebert    |                    Owner:  nobody
         Type:  Uncategorized   |                   Status:  new
    Component:  Uncategorized   |                  Version:  2.0
     Severity:  Normal          |               Resolution:
     Keywords:  QuerySet.extra  |             Triage Stage:  Unreviewed
    Has patch:  0               |      Needs documentation:  0
  Needs tests:  0               |  Patch needs improvement:  0
Easy pickings:  0               |                    UI/UX:  0
--------------------------------+--------------------------------------

Comment (by Ryan Hiebert):

 With the help of a patient colleague (thanks Tim!) I've been able to
 accomplish what I needed to natively, without using {{{.extra()}}}. With
 one caveat, I needed to add the LHS as a calculated column using annotate,
 which is a bit of a kludge, which ends up returning annotated data that I
 didn't really need. For my case, that's not too big of a deal, but perhaps
 less than ideal.

 It might be deserving of a way to remove annotations that don't need to be
 selected, or to allow filter expressions that allow a dynamic expression
 on both sides. I'm not sure if that deserves its own ticket, if it should
 be on this one, or if perhaps there's already a ticket open for that.

 Here's what we came up with:

 {{{#!python
 from django.db.models import Func, F, Subquery

 def after(queryset, value):
     fields = ['a', 'b', 'c', 'id']
     return (
         queryset
         .annotate(rank=Func(*(F(field) for field in fields),
 function='ROW'))
         .filter(rank=Subquery(queryset.filter(id=value).values(*fields)))
         .order_by(*fields)
     )
 }}}

 One other thing to note is that this opts to use the explicit {{{ROW}}}
 function, rather than relying on that being the result of just using
 parenthesis, because parenthesis alone with a single value doesn't
 necessarily make a {{{ROW}}}.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/29527#comment:1>
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 post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/069.832fa3e6c31326b13e3390afd7d02584%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to