Skip to content

Commit 386257b

Browse files
authored
Refs #36494 -- Prevented crash in JSONField numeric lookups with expressions.
1 parent 10ea59b commit 386257b

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

django/db/models/fields/json.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -698,8 +698,8 @@ class KeyTransformIRegex(
698698
class KeyTransformNumericLookupMixin:
699699
def process_rhs(self, compiler, connection):
700700
rhs, rhs_params = super().process_rhs(compiler, connection)
701-
if not connection.features.has_native_json_field:
702-
rhs_params = [json.loads(value) for value in rhs_params]
701+
if not connection.features.has_native_json_field and self.rhs_is_direct_value():
702+
rhs_params = tuple(json.loads(value) for value in rhs_params)
703703
return rhs, rhs_params
704704

705705

tests/model_fields/test_jsonfield.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1304,6 +1304,35 @@ def test_json_type_casting_with_coalesce(self):
13041304
).first()
13051305
self.assertEqual(result.coalesced_value, "This is valid JSON primitive.")
13061306

1307+
def test_numeric_lookups_with_expression(self):
1308+
obj_greater = NullableJSONModel.objects.create(
1309+
value={"target": 5, "comparison": 2}
1310+
)
1311+
obj_lesser = NullableJSONModel.objects.create(
1312+
value={"target": 2, "comparison": 5}
1313+
)
1314+
obj_equal = NullableJSONModel.objects.create(
1315+
value={"target": 2, "comparison": 2}
1316+
)
1317+
objs = [obj_greater.pk, obj_lesser.pk, obj_equal.pk]
1318+
1319+
tests = [
1320+
("gt", [obj_greater]),
1321+
("lt", [obj_lesser]),
1322+
("gte", [obj_greater, obj_equal]),
1323+
("lte", [obj_lesser, obj_equal]),
1324+
]
1325+
1326+
for lookup, expected in tests:
1327+
with self.subTest(lookup=lookup):
1328+
self.assertCountEqual(
1329+
NullableJSONModel.objects.filter(
1330+
id__in=objs,
1331+
**{f"value__target__{lookup}": F("value__comparison")},
1332+
),
1333+
expected,
1334+
)
1335+
13071336

13081337
@skipUnlessDBFeature("supports_primitives_in_json_field")
13091338
class JSONNullTests(TestCase):

0 commit comments

Comments
 (0)