#18333 closed Bug (fixed)
Aggregating an annotated field does not quote the alias column name
Reported by: | Michael Manfre | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | aggregate, annotate |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Given the below code snippet from aggregation.BaseAggregateTestCase.test_aggregate_annotation:
vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate(Avg("num_authors"))
The generated SQL does not quote the annotated field "num_authors" when used with the aggregate function. Generated SQL is of the form:
SELECT AVG(num_authors) FROM (... subquery ...)
Attachments (2)
Change History (10)
by , 13 years ago
Attachment: | django-ticket18333.diff added |
---|
by , 13 years ago
Attachment: | django-ticket18333.2.diff added |
---|
comment:1 by , 13 years ago
comment:3 by , 12 years ago
Seems like if you use a SQL reserved keyword as the key in annotate, then you will get a broken query. No testing done here.
comment:4 by , 12 years ago
Needs tests: | set |
---|---|
Triage Stage: | Unreviewed → Accepted |
Ah, I see, I was just thinking about characters that can't be part of keyword arguments anyway, so thought there wasn't an issue.
comment:5 by , 11 years ago
Updated pull request with test. https://github.com/django/django/pull/1674
comment:6 by , 11 years ago
Needs tests: | unset |
---|
comment:7 by , 11 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
I'm not aware of any databases that need to quote '*', but just in case there are I provided two patches. The second preloads the cache with '*' to prevent quoting it. Most commonly encountered by COUNT(*). Regardless of which patch is chosen (if any), 3rd party backends can override quote_cache to either have or omit this initial alias.