#30130: Django .values().distinct() returns a lot more records than
.values().distinct().count()
-------------------------------------+-------------------------------------
     Reporter:  James Lin            |                    Owner:  nobody
         Type:  Bug                  |                   Status:  new
    Component:  Database layer       |                  Version:  2.1
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:                       |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by Simon Charette):

 I'm pretty sure that's what's at play here as I managed to reproduce
 locally. You have a defined `Meta.ordering` (or are performing an
 `order_by`) which makes your non-count query something along the lines of

 {{{#!sql
 SELECT DISTINCT "machine", "cluster", "ordering" FROM "resources" ORDER BY
 "ordering" ASC
 }}}

 The `ordering` column is added to the `SELECT` clause to prevent the
 generation of invalid SQL.

 {{{#!sql
 SELECT DISTINCT "machine", "cluster" FROM "resources" ORDER BY "ordering"
 ASC
 > ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select
 list
 }}}

 The `.count()` query happens to be the following

 {{{#!sql
 SELECT COUNT(*) FROM (SELECT DISTINCT "ticket_30130_foo"."bat" AS Col1,
 "ticket_30130_foo"."baz" AS Col2 FROM "ticket_30130_foo") subquery
 }}}

 It looks like the issue is that
 
[https://github.com/django/django/blob/7e978fdc4228eb44cf97cb4243adc7b7bfd586c7/django/db/models/sql/query.py#L439-L443
 we clear the ordering when we shouldn't] on the `.count()`. I think the
 logic needs to be adjusted to branch of `not self.distinct` instead of
 `self.distinct_fields`.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/30130#comment:4>
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/066.391f20ea758b15f7eac92c14b96f6eac%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to