From 9b6ec014aa39ddffc204323cb6045c6b4655c3bf Mon Sep 17 00:00:00 2001 From: Martin Schwinzerl Date: Sat, 2 Dec 2023 13:34:30 +0100 Subject: [PATCH 1/2] Attempts to fix update_change_reason for nullable JSONField fields As reported in issue #1181, the implementation of the utility `update_change_reason()` method does not work for models with a nullable JSONField. This is caused by the slightly more convoluted querying mechanisms that have to be applied for JSONFields, please cf. here: [django dev documentation](https://docs.djangoproject.com/en/dev/topics/db/queries/#querying-jsonfield) This attempts to fix this by assuming that - a nullable JSONField with a `value` of `None` is not set at all - a non-nullable JSONField with a `value` of `None` is actually a "NULL" dictionary I am aware that this is not the only way to handle this. But it is the convention I am using in my project and this fixed the issue for me. It may be worthwhile to implement a policy switch to decide how to interpret `None` in this specific case. --- simple_history/utils.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/simple_history/utils.py b/simple_history/utils.py index 321ec147d..0733489eb 100644 --- a/simple_history/utils.py +++ b/simple_history/utils.py @@ -1,5 +1,5 @@ from django.db import transaction -from django.db.models import Case, ForeignKey, ManyToManyField, Q, When +from django.db.models import Case, ForeignKey, ManyToManyField, Q, When, JSONField, Value from django.forms.models import model_to_dict from simple_history.exceptions import AlternativeManagerError, NotHistoricalModelError @@ -18,6 +18,11 @@ def update_change_reason(instance, reason): if field.primary_key is True: if value is not None: attrs[field.attname] = value + elif isinstance(field, JSONField): + if value is None and field.null is True: + attrs[f"{field.attname}__isnull"] = True + else: + attrs[field.attname] = Value(value, JSONField()) else: attrs[field.attname] = value From 7ea2597339215845df911da8dd152aff26c0c342 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 2 Dec 2023 13:02:13 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- simple_history/utils.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/simple_history/utils.py b/simple_history/utils.py index 0733489eb..c809bbaa8 100644 --- a/simple_history/utils.py +++ b/simple_history/utils.py @@ -1,5 +1,13 @@ from django.db import transaction -from django.db.models import Case, ForeignKey, ManyToManyField, Q, When, JSONField, Value +from django.db.models import ( + Case, + ForeignKey, + JSONField, + ManyToManyField, + Q, + Value, + When, +) from django.forms.models import model_to_dict from simple_history.exceptions import AlternativeManagerError, NotHistoricalModelError