#26925 closed Cleanup/optimization (fixed)
Add a link to aggregation ordering interaction from Meta.ordering docs
Reported by: | Nicolas Joyard | Owned by: | nobody |
---|---|---|---|
Component: | Documentation | Version: | 1.8 |
Severity: | Normal | Keywords: | aggregation |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Consider the following model definition:
class Thing(Model): foo = SomeField() bar = SomeField() class Meta: ordering = ('foo',)
Imagine I would like to count instances of Things for each 'bar' value:
qs = Thing.objects.all.values('bar').annotate(cnt=Count('bar'))
I would expect the ORM to execute something along the lines of
SELECT bar, COUNT(bar) FROM things GROUP BY bar
Except the ORM wants to enforce the default ordering, and the only way to do so is to execute
SELECT bar, COUNT(bar) FROM things GROUP BY foo, bar ORDER BY foo
...which is a completely different query. As a user of the model, I have to add an ordering override (that I didn't need and that adds an ordering step in the query execution plan):
qs = Thing.objects.all.values('bar').annotate(cnt=Count('bar')).order_by('bar')
I would expect the ORM to either:
- ignore the default ordering, given that it uses fields that are no longer retrieved in the query
- fail executing the query with an exception stating that my aggregation is not compatible with the model default ordering
Change History (6)
comment:1 by , 8 years ago
comment:3 by , 8 years ago
Component: | Database layer (models, ORM) → Documentation |
---|---|
Has patch: | set |
Summary: | ORM changes grouping when default ordering is set → Add a link to aggregation ordering interaction from Meta.ordering docs |
Triage Stage: | Unreviewed → Accepted |
Type: | Bug → Cleanup/optimization |
PR to add a doc link.
Note:
See TracTickets
for help on using tickets.
I'm tempted to close this as wontfix since this is a documented caveat of aggregating over a model with a default
ordering
.Maybe we could add another warning to the
Meta.ordering
docs pointing to aforementioned caveat as silently ignoring the ordering is not an option at this point as it would be backward incompatible.