From 74630a9441fe3d6467db4336e3ea44b47c3ea4d6 Mon Sep 17 00:00:00 2001 From: Birger Schacht Date: Tue, 7 May 2024 14:07:59 +0200 Subject: [PATCH] fix(history): use signal instead of method for setting timestamp When doing a CASCADING delete, the `delete` method of an instance is not called, but the `pre_delete` signal is triggered. We want to set the current date for the `_history_date` attribute, if it is None. To do that also in cascading deletes, we use the pre_delete signal. Closes: #814 --- apis_core/history/apps.py | 3 +++ apis_core/history/models.py | 5 ----- apis_core/history/signals.py | 9 +++++++++ 3 files changed, 12 insertions(+), 5 deletions(-) create mode 100644 apis_core/history/signals.py diff --git a/apis_core/history/apps.py b/apis_core/history/apps.py index 959a885a1..93c560959 100644 --- a/apis_core/history/apps.py +++ b/apis_core/history/apps.py @@ -3,3 +3,6 @@ class HistoryConfig(AppConfig): name = "apis_core.history" + + def ready(self): + from . import signals # noqa: F401 diff --git a/apis_core/history/models.py b/apis_core/history/models.py index d53059db7..9bd9afb97 100644 --- a/apis_core/history/models.py +++ b/apis_core/history/models.py @@ -148,11 +148,6 @@ def save(self, *args, **kwargs) -> None: self._history_date = timezone.now() return super().save(*args, **kwargs) - def delete(self, *args, **kwargs) -> tuple[int, dict[str, int]]: - if self._history_date is None: - self._history_date = datetime.now() - return super().delete(*args, **kwargs) - def get_history_url(self): ct = ContentType.objects.get_for_model(self) return reverse("apis_core:history:history", args=[ct, self.id]) diff --git a/apis_core/history/signals.py b/apis_core/history/signals.py new file mode 100644 index 000000000..23a4db7ea --- /dev/null +++ b/apis_core/history/signals.py @@ -0,0 +1,9 @@ +from django.db.models.signals import pre_delete +from django.dispatch import receiver +from django.utils import timezone + + +@receiver(pre_delete) +def set_history_date(sender, instance, using, origin, **kwargs): + if getattr(instance, "_history_date", None) is None: + instance._history_date = timezone.now()