#26925: ORM changes grouping when default ordering is set
----------------------------------------------+-------------------------
     Reporter:  njoyard                       |      Owner:  nobody
         Type:  Bug                           |     Status:  new
    Component:  Database layer (models, ORM)  |    Version:  1.8
     Severity:  Normal                        |   Keywords:  aggregation
 Triage Stage:  Unreviewed                    |  Has patch:  0
Easy pickings:  0                             |      UI/UX:  0
----------------------------------------------+-------------------------
 Consider the following model definition:
 {{{
 class Thing(Model):
     foo = SomeField()
     bar = SomeField()

     class Meta:
         ordering = ('foo',)
 }}}

 Imagine I would like to count instances of Things for each 'bar' value:
 {{{
 qs = Thing.objects.all.values('bar').annotate(cnt=Count('bar'))
 }}}

 I would expect the ORM to execute something along the lines of
 {{{
 SELECT bar, COUNT(bar) FROM things GROUP BY bar
 }}}

 Except the ORM wants to enforce the default ordering, and the only way to
 do so is to execute
 {{{
 SELECT bar, COUNT(bar) FROM things GROUP BY foo, bar ORDER BY foo
 }}}

 ...which is a completely different query. As a user of the model, I have
 to add an ordering override (that I didn't need and that adds an ordering
 step in the query execution plan):
 {{{
 qs =
 Thing.objects.all.values('bar').annotate(cnt=Count('bar')).order_by('bar')
 }}}

 I would expect the ORM to either:
 - ignore the default ordering, given that it uses fields that are no
 longer retrieved in the query
 - fail executing the query with an exception stating that my aggregation
 is not compatible with the model default ordering

--
Ticket URL: <https://code.djangoproject.com/ticket/26925>
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/050.f17304f104654758e719766399cd18b6%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to