#30685: Suboptimal QuerySet.distinct().count()
-------------------------------------+-------------------------------------
Reporter: Adam Sołtysik | Owner: nobody
Type: | Status: new
Cleanup/optimization |
Component: Database layer | Version: 2.2
(models, ORM) |
Severity: Normal | Resolution:
Keywords: | Triage Stage: Accepted
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Adam Sołtysik):
Thank you for accepting. I have added `.values('pk').order_by()` before my
`.count()` queries, but I'll be glad to be able to get rid of it.
Just to add a bit more information. The "problem" is not only with
`.distinct()`, also any `.annotate()` makes `count()` produce a subquery
with the redundant annotations inside. For example, a query like this
results in SQL that is 4 times slower for my data than the bare count:
{{{Model.objects.annotate(id2=F('id')).count()}}}
{{{(0.057) SELECT COUNT(*) FROM (SELECT "table"."id" AS Col1, "table"."id"
AS "id2" FROM "table" GROUP BY "table"."id") subquery;}}}
Adding `.values('pk')` of course solves this as well.
--
Ticket URL: <https://code.djangoproject.com/ticket/30685#comment:6>
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/065.64f6f82f6b1522b1edbe9d926e66d160%40djangoproject.com.