Aggregating when grouping on an ExpressionWrapper omits the expression from the group by
I ran into this with Postgres on Django 3.1.3, I'm not sure what other versions it exists on.
print(
Fred.objects.annotate(
bob_id__is_null=ExpressionWrapper(
Q(bob_id=None),
output_field=BooleanField()
)
).values(
"bob_id__is_null"
).annotate(
id__count=Count("id", distinct=True)
).values(
"bob_id__is_null",
"id__count"
).query
)
SELECT
"main_fred"."bob_id" IS NULL AS "bob_id__is_null",
COUNT(DISTINCT "main_fred"."id") AS "id__count"
FROM "main_fred"
GROUP BY "main_fred"."bob_id"
On the last line there the group by has dropped the "IS NULL"
Change History
(11)
| Component: |
Uncategorized → Database layer (models, ORM)
|
| Severity: |
Normal → Release blocker
|
| Triage Stage: |
Unreviewed → Accepted
|
| Type: |
Uncategorized → Bug
|
| Cc: |
Simon Charette Thodoris Sotiropoulos added
|
| Has patch: |
set
|
| Owner: |
changed from nobody to Hasan Ramezani
|
| Status: |
new → assigned
|
| Needs documentation: |
set
|
| Patch needs improvement: |
set
|
| Needs documentation: |
unset
|
| Patch needs improvement: |
unset
|
| Triage Stage: |
Accepted → Ready for checkin
|
| Resolution: |
→ fixed
|
| Status: |
assigned → closed
|
For anyone else who ends up here you can Subquery your way out of this, although I've no idea what the performance implications of that are.