summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorshanghui <shangdahao@gmail.com>2017-09-01 14:26:09 +0800
committerTim Graham <timograham@gmail.com>2017-11-11 19:45:23 -0500
commit1907fc9b1292a55f1b8d54f4dbcdbda16bbb36c1 (patch)
treeaee0976a973ccfff14450c079d61772e488dcc33
parentbdb747a5f2ffe7356c722c67184a2bc1e24c7f73 (diff)
Fixed #28534 -- Made JSONField.has_changed() ignore key order and consider True/1 values as different.
-rw-r--r--django/contrib/postgres/forms/jsonb.py8
-rw-r--r--tests/postgres_tests/test_json.py5
2 files changed, 13 insertions, 0 deletions
diff --git a/django/contrib/postgres/forms/jsonb.py b/django/contrib/postgres/forms/jsonb.py
index 158ab8fdb9..bb681e0be3 100644
--- a/django/contrib/postgres/forms/jsonb.py
+++ b/django/contrib/postgres/forms/jsonb.py
@@ -52,3 +52,11 @@ class JSONField(forms.CharField):
if isinstance(value, InvalidJSONInput):
return value
return json.dumps(value)
+
+ def has_changed(self, initial, data):
+ if super().has_changed(initial, data):
+ return True
+ # For purposes of seeing whether something has changed, True isn't the
+ # same as 1 and the order of keys doesn't matter.
+ data = self.to_python(data)
+ return json.dumps(initial, sort_keys=True) != json.dumps(data, sort_keys=True)
diff --git a/tests/postgres_tests/test_json.py b/tests/postgres_tests/test_json.py
index acbd855f1a..a572e670ac 100644
--- a/tests/postgres_tests/test_json.py
+++ b/tests/postgres_tests/test_json.py
@@ -410,3 +410,8 @@ class TestFormField(PostgreSQLTestCase):
for json_string in tests:
val = field.clean(json_string)
self.assertEqual(field.clean(val), val)
+
+ def test_has_changed(self):
+ field = forms.JSONField()
+ self.assertIs(field.has_changed({'a': True}, '{"a": 1}'), True)
+ self.assertIs(field.has_changed({'a': 1, 'b': 2}, '{"b": 2, "a": 1}'), False)