diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index 9ee2d65c8a..f25ad1af12 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -402,10 +402,13 @@ class BaseExpression: return clone def replace_expressions(self, replacements): + if not replacements: + return self if replacement := replacements.get(self): return replacement + if not (source_expressions := self.get_source_expressions()): + return self clone = self.copy() - source_expressions = clone.get_source_expressions() clone.set_source_expressions( [ expr.replace_expressions(replacements) if expr else None diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index a79d66eb21..ce4fafb1e2 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -972,6 +972,8 @@ class Query(BaseExpression): relabelling any references to them in select columns and the where clause. """ + if not change_map: + return self # If keys and values of change_map were to intersect, an alias might be # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending # on their order in change_map. diff --git a/django/db/models/sql/where.py b/django/db/models/sql/where.py index 2f23a2932c..8423fcb528 100644 --- a/django/db/models/sql/where.py +++ b/django/db/models/sql/where.py @@ -204,6 +204,8 @@ class WhereNode(tree.Node): Relabel the alias values of any children. 'change_map' is a dictionary mapping old (current) alias values to the new values. """ + if not change_map: + return self for pos, child in enumerate(self.children): if hasattr(child, "relabel_aliases"): # For example another WhereNode @@ -225,6 +227,8 @@ class WhereNode(tree.Node): return clone def replace_expressions(self, replacements): + if not replacements: + return self if replacement := replacements.get(self): return replacement clone = self.create(connector=self.connector, negated=self.negated)