summaryrefslogtreecommitdiff
path: root/django/db/models/sql/compiler.py
diff options
context:
space:
mode:
Diffstat (limited to 'django/db/models/sql/compiler.py')
-rw-r--r--django/db/models/sql/compiler.py39
1 files changed, 4 insertions, 35 deletions
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index b6574eab2e..97c7ba2013 100644
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -179,41 +179,10 @@ class SQLCompiler:
return result
def collapse_group_by(self, expressions, having):
- # If the DB can group by primary key, then group by the primary key of
- # query's main model. Note that for PostgreSQL the GROUP BY clause must
- # include the primary key of every table, but for MySQL it is enough to
- # have the main table's primary key.
- if self.connection.features.allows_group_by_pk:
- # Determine if the main model's primary key is in the query.
- pk = None
- for expr in expressions:
- # Is this a reference to query's base table primary key? If the
- # expression isn't a Col-like, then skip the expression.
- if (
- getattr(expr, "target", None) == self.query.model._meta.pk
- and getattr(expr, "alias", None) == self.query.base_table
- ):
- pk = expr
- break
- # If the main model's primary key is in the query, group by that
- # field, HAVING expressions, and expressions associated with tables
- # that don't have a primary key included in the grouped columns.
- if pk:
- pk_aliases = {
- expr.alias
- for expr in expressions
- if hasattr(expr, "target") and expr.target.primary_key
- }
- expressions = [pk] + [
- expr
- for expr in expressions
- if expr in having
- or (
- getattr(expr, "alias", None) is not None
- and expr.alias not in pk_aliases
- )
- ]
- elif self.connection.features.allows_group_by_selected_pks:
+ # If the database supports group by functional dependence reduction,
+ # then the expressions can be reduced to the set of selected table
+ # primary keys as all other columns are functionally dependent on them.
+ if self.connection.features.allows_group_by_selected_pks:
# Filter out all expressions associated with a table's primary key
# present in the grouped columns. This is done by identifying all
# tables that have their primary key included in the grouped