#32152: Groupby after aggregation and subquery produces subtly wrong results
-------------------------------------+-------------------------------------
Reporter: Christian Klus | Owner: nobody
Type: Bug | Status: new
Component: Database layer | Version: 3.1
(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
-------------------------------------+-------------------------------------
Changes (by Simon Charette):
* stage: Unreviewed => Accepted
Comment:
Thanks for the report and test Christian, I think you analysis is right;
all members of the `SELECT` clause should be considered.
Could you submit a PR on Github including your test and the following
changes
{{{#!diff
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index ee98984826..96819803c0 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -2205,8 +2205,10 @@ def set_values(self, fields):
field_names.append(f)
self.set_extra_mask(extra_names)
self.set_annotation_mask(annotation_names)
+ selected = frozenset(field_names + extra_names +
annotation_names)
else:
field_names = [f.attname for f in
self.model._meta.concrete_fields]
+ selected = frozenset(field_names)
# Selected annotations must be known before setting the GROUP BY
# clause.
if self.group_by is True:
@@ -2220,7 +2222,7 @@ def set_values(self, fields):
# the selected fields anymore.
group_by = []
for expr in self.group_by:
- if isinstance(expr, Ref) and expr.refs not in
field_names:
+ if isinstance(expr, Ref) and expr.refs not in selected:
expr = self.annotations[expr.refs]
group_by.append(expr)
self.group_by = tuple(group_by)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/32152#comment:3>
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.7eb0c4715d8bead8e7d66a3a6c6fe702%40djangoproject.com.