From 0ec60661e61b153e6bcec64649b1b7f524eb3e18 Mon Sep 17 00:00:00 2001 From: Julie Rymer Date: Mon, 15 May 2023 15:19:38 +0200 Subject: [PATCH] Fixed #34539 -- Restored get_prep_value() call when adapting JSONFields. Regression in 5c23d9f0c32f166c81ecb6f3f01d5077a6084318. --- AUTHORS | 1 + django/db/models/fields/json.py | 2 ++ docs/releases/4.2.2.txt | 3 +++ tests/model_fields/test_jsonfield.py | 23 +++++++++++++++++++++++ 4 files changed, 29 insertions(+) diff --git a/AUTHORS b/AUTHORS index 291b5da657..d4d2c47d93 100644 --- a/AUTHORS +++ b/AUTHORS @@ -532,6 +532,7 @@ answer newbie questions, and generally made Django that much better: Julia Elman Julia Matsieva Julian Bez + Julie Rymer Julien Phalip Junyoung Choi junzhang.jn@gmail.com diff --git a/django/db/models/fields/json.py b/django/db/models/fields/json.py index eb2d35f100..b7cde157c4 100644 --- a/django/db/models/fields/json.py +++ b/django/db/models/fields/json.py @@ -99,6 +99,8 @@ class JSONField(CheckFieldDefaultMixin, Field): return "JSONField" def get_db_prep_value(self, value, connection, prepared=False): + if not prepared: + value = self.get_prep_value(value) # RemovedInDjango51Warning: When the deprecation ends, replace with: # if ( # isinstance(value, expressions.Value) diff --git a/docs/releases/4.2.2.txt b/docs/releases/4.2.2.txt index 9d16e7ef6f..a92582b7a0 100644 --- a/docs/releases/4.2.2.txt +++ b/docs/releases/4.2.2.txt @@ -12,3 +12,6 @@ Bugfixes * Fixed a regression in Django 4.2 that caused an unnecessary ``DBMS_LOB.SUBSTR()`` wrapping in the ``__isnull`` and ``__exact=None`` lookups for ``TextField()``/``BinaryField()`` on Oracle (:ticket:`34544`). + +* Restored, following a regression in Django 4.2, ``get_prep_value()`` call in + ``JSONField`` subclasses (:ticket:`34539`). diff --git a/tests/model_fields/test_jsonfield.py b/tests/model_fields/test_jsonfield.py index 60357d87b2..4a1cc075b4 100644 --- a/tests/model_fields/test_jsonfield.py +++ b/tests/model_fields/test_jsonfield.py @@ -103,6 +103,29 @@ class TestMethods(SimpleTestCase): with self.assertRaisesMessage(TypeError, msg): KeyTransformTextLookupMixin(transform) + def test_get_prep_value(self): + class JSONFieldGetPrepValue(models.JSONField): + def get_prep_value(self, value): + if value is True: + return {"value": True} + return value + + def noop_adapt_json_value(value, encoder): + return value + + field = JSONFieldGetPrepValue() + with mock.patch.object( + connection.ops, "adapt_json_value", noop_adapt_json_value + ): + self.assertEqual( + field.get_db_prep_value(True, connection, prepared=False), + {"value": True}, + ) + self.assertIs( + field.get_db_prep_value(True, connection, prepared=True), True + ) + self.assertEqual(field.get_db_prep_value(1, connection, prepared=False), 1) + class TestValidation(SimpleTestCase): def test_invalid_encoder(self):