#28477: Strip unused annotations from count queries
-------------------------------------+-------------------------------------
     Reporter:  Tom Forbes           |                    Owner:  Tom
         Type:                       |  Forbes
  Cleanup/optimization               |                   Status:  assigned
    Component:  Database layer       |                  Version:  master
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:                       |             Triage Stage:  Accepted
    Has patch:  1                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  1
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by Reupen Shah):

 The behaviour is actually a bit more bizarre than I thought.

 With the same person model, here are four count variations and the
 generated queries:

 1.

 {{{
 Person.objects.count()
 }}}

 {{{
 SELECT COUNT(*) AS "__count" FROM "people_person"
 }}}

 2.

 {{{
 Person.objects.values('pk').count()
 }}}

 {{{
 SELECT COUNT(*) AS "__count" FROM "people_person"
 }}}

 3.

 {{{
 Person.objects.annotate(full_name=Concat('first_name', Value(' '),
 'last_name')).count()
 }}}

 {{{
 SELECT COUNT(*) FROM (SELECT "people_person"."id" AS Col1,
 CONCAT("people_person"."first_name", CONCAT(' ',
 "people_person"."last_name")) AS "full_name" FROM "people_person" GROUP BY
 "people_person"."id", CONCAT("people_person"."first_name", CONCAT(' ',
 "people_person"."last_name"))) subquery
 }}}

 4.

 {{{
 Person.objects.annotate(full_name=Concat('first_name', Value(' '),
 'last_name')).values('pk').count()
 }}}

 {{{
 SELECT COUNT(*) FROM (SELECT "people_person"."id" AS Col1 FROM
 "people_person") subquery
 }}}


 So there's a simple workaround for the case I gave in my last comment in
 calling `.values('pk')` before `.count()`. However, that's not much help
 if Django or other libraries are the ones calling `.count()`.

 On the plus side, I have a better understanding of what the problem is
 from looking at the Django source code.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/28477#comment:9>
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 django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/061.3a64851e336b74aa6e2351e7d22137f9%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to