Annotate() doesn't error if given a previously defined annotation alias
|Reported by:||aseering@…||Owned by:|
|Component:||Database layer (models, ORM)||Version:||1.0|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Description (last modified by Alex)
I recently wrote the following code:
classes = classes.annotate(num_students=Count('anchor__child_set__userbit_qsc')) classes = classes.annotate(total_max_student=Sum('sections__num_students'))
The second line above (correctly) generated an error for me because the model referenced by "sections" doesn't contain a field named "num_students".
However, the error message returned by the exception was as follows:
Cannot resolve keyword 'num_students' into field. Choices are: [long valid list of fields], num_students
This confused me for a good while (until I realized that it was my mistake for using the wrong field name). On experimentation, the "num_students" in the list of fields does in fact come from the first annotate call.
It's hardly a critical failure; but it seems like poor form to declare a field as "invalid" then promptly list it as one of the valid options... More generally, it seems like that list just lists all annotated fields, which is only correct if you're not doing a join first.
I suspect that the fix is on line 1678 or so of django/db/models/sql/query.py (in particular, maybe it needs to use a different/new function on the Options class to get the keys properly?); but I don't know enough of those internals to know that I'm doing the right thing there. I could work up a patch that does this if no one more-experienced feels like it or knows of a good reason not to.
Change History (5)
comment:1 Changed 7 years ago by Alex
- Description modified (diff)
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:2 Changed 7 years ago by russellm
- Component changed from Uncategorized to ORM aggregation
- milestone set to 1.1
- Owner nobody deleted
- Summary changed from Confusing error message on invalid annotate aggregate field to Annotate() doesn't error if given a previously defined annotation alias
- Triage Stage changed from Unreviewed to Accepted