From 33c06ca0da6c4f151b84e5d8c305faff9ca30d98 Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Wed, 13 Mar 2024 17:46:37 +0100 Subject: [PATCH] Refs #32673, Refs #35295 -- Avoided wrapping rhs direct values in lookups. --- django/db/models/lookups.py | 2 +- tests/lookup/tests.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index 139875eed5..18c4f2ca08 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -122,7 +122,7 @@ class Lookup(Expression): # Ensure expression is wrapped in parentheses to respect operator # precedence but avoid double wrapping as it can be misinterpreted # on some backends (e.g. subqueries on SQLite). - if sql and sql[0] != "(": + if not isinstance(value, Value) and sql and sql[0] != "(": sql = "(%s)" % sql return sql, params else: diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py index a198a13b62..ebdaa21e3d 100644 --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -1366,6 +1366,12 @@ class LookupTests(TestCase): [stock_1, stock_2], ) + def test_lookup_direct_value_rhs_unwrapped(self): + with self.assertNumQueries(1) as ctx: + self.assertIs(Author.objects.filter(GreaterThan(2, 1)).exists(), True) + # Direct values on RHS are not wrapped. + self.assertIn("2 > 1", ctx.captured_queries[0]["sql"]) + class LookupQueryingTests(TestCase): @classmethod