Opened 15 months ago

Last modified 6 weeks ago

#28477 assigned Cleanup/optimization

Strip unused annotations from count queries

Reported by: Tom Forbes Owned by: Tom Forbes
Component: Database layer (models, ORM) Version: master
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

The query below produces a SQL statement that includes the Count('chapters'), despite not not being used in any filter operations.

Book.objects.annotate(Count('chapters')).count()

It produces the same results as:

Book.objects.count()

Django could be more intelligent about what annotations to include in the query produced by queryset.count(), stripping out any annotations that are not referenced by filters, other annotations or ordering. This should speed up calls to count() with complex annotations.

There seems to be precedent for this: select_related calls are ignored with count() queries.

Change History (6)

comment:1 Changed 15 months ago by Tim Graham

Triage Stage: UnreviewedAccepted

comment:2 Changed 15 months ago by Tom Forbes

Owner: changed from nobody to Tom Forbes
Status: newassigned

comment:3 Changed 15 months ago by Tom Forbes

Same can be done for exists()

comment:5 Changed 7 weeks ago by Simon Charette

Has patch: set

comment:6 Changed 6 weeks ago by Tim Graham

Patch needs improvement: set

The PR is still marked [WIP] and there are test failures.

Note: See TracTickets for help on using tickets.
Back to Top