#32828: Wrong .count() for GROUP BY on ordered queryset
-------------------------------------+-------------------------------------
     Reporter:  Maxim Petrov         |                    Owner:  nobody
         Type:  Bug                  |                   Status:  closed
    Component:  Database layer       |                  Version:  3.2
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:  invalid
     Keywords:                       |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Changes (by Mariusz Felisiak):

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


Comment:

 Thanks for this report, however these queries can return different results
 (see also #30655).

 `count()` calls `SELECT COUNT(*)` (as described in
 [https://docs.djangoproject.com/en/stable/ref/models/querysets/#count
 docs]) without taking ordering into account, so in your case it returns
 the number of `Foo`'s names (this behavior is in Django since
 7bc57a6d71dd4d00bb09cfa67be547591fd759ce).

 It can be surprising that columns from `order_by()` calls are included in
 the `GROUP BY` clauses, that's we it's
 [https://docs.djangoproject.com/en/3.2/topics/db/aggregation/#interaction-
 with-default-ordering-or-order-by documented].

 To get the same results you can clear ordering or add `data` to the
 `values()`:

 {{{
 
Foo.objects.order_by("date").values("name").annotate(models.Count("name")).order_by()
 Foo.objects.order_by("date").values("name",
 "date").annotate(models.Count("name"))
 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/32828#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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/069.07dae2820b922dde36f1d2e6941a8c23%40djangoproject.com.

Reply via email to