#31109: Multiple annotation with Subquery generates wrong SQL. -------------------------------------+------------------------------------- Reporter: Thierry Bastian | Owner: nobody Type: Bug | Status: new Component: Database layer | Version: 3.0 (models, ORM) | Severity: Release blocker | Resolution: Keywords: | Triage Stage: Accepted Has patch: 0 | Needs documentation: 0 Needs tests: 0 | Patch needs improvement: 0 Easy pickings: 0 | UI/UX: 0 -------------------------------------+-------------------------------------
Comment (by Simon Charette): So here's what happens here. 1. Since `StringAgg` is an aggregate it sets `queryset.query.group_by = True` on annotation. 2. `QuerySet.exists()` relies on `Query.has_results` 3. `Query.has_results` does the following when `distinct=False` and `group_by=True`. 1. It adds all the the concrete fields of the model to address #24835 2. Calls `set_group_by` which happens to add a `Ref` referring to the selected `Subquery` annotation to `group_by` since fb3f034f1c63160c0ff13c609acd01c18be12f80 . 3. It then calls `clear_select_clause` which orphans the `Ref` since it now points to column that isn't referenced to anymore. The solutions is either to: a. Add a parameter to `Query.set_group_by` to prevent `GROUP BY` by aliases; effectively passing `alias=None` to all its `annotation.get_group_by_cols` calls. b. Make `clear_select_clause` remove all `Ref` to `annotation_select` entries from `group_by` before calling `set_annotation_mask(())`. a. is likely less invasive and seems more correct given the sole caller requiring this behaviour does so because it knows it'll call `clear_select_clause` right after. -- Ticket URL: <https://code.djangoproject.com/ticket/31109#comment:4> 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 django-updates+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/067.3f6c3e0b8d361a262483d64cc99bd559%40djangoproject.com.