# django__django-12589 # Loki Mode Multi-Agent Patch # Attempts: 1 Based on the architect's analysis and the issue description, I can generate the patch. The issue is in the `set_group_by` method in `django/db/models/sql/query.py` where the alias is used in GROUP BY without checking for column name collisions. --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1940,6 +1940,20 @@ class Query(BaseExpression): # already part of the select clause. continue for alias, annotation in self.annotation_select.items(): - cols = annotation.get_group_by_cols(alias=alias) + # Check if the alias collides with any column name in joined tables. + # If so, we need to use the full expression instead of the alias + # to avoid ambiguous column reference errors in the GROUP BY clause. + col_alias = alias + for table_alias, table in self.alias_map.items(): + if hasattr(table, 'table_name'): + # Check if any column in this table has the same name as our alias + from django.db import connection + table_info = connection.introspection.get_table_description( + connection.cursor(), table.table_name + ) + if any(col.name == alias for col in table_info): + col_alias = None + break + cols = annotation.get_group_by_cols(alias=col_alias) group_by.extend(cols) self.group_by = tuple(group_by) Wait, this approach using introspection at query time is too expensive. Let me reconsider with a simpler approach that checks column references in the query itself: --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1940,7 +1940,22 @@ class Query(BaseExpression): # already part of the select clause. continue for alias, annotation in self.annotation_select.items(): - cols = annotation.get_group_by_cols(alias=alias) + # Check if the alias collides with any column name in joined tables. + # If so, we need to use the full expression instead of the alias + # to avoid ambiguous column reference errors in the GROUP BY clause. + col_alias = alias + for join in self.alias_map.values(): + if hasattr(join, 'join_cols'): + # Check join columns for name collision + for lhs_col, rhs_col in join.join_cols: + if lhs_col == alias or rhs_col == alias: + col_alias = None + break + if col_alias is None: + break + cols = annotation.get_group_by_cols(alias=col_alias) group_by.extend(cols) self.group_by = tuple(group_by)