Skip to content

Commit

Permalink
fix(history): use signal instead of method for setting timestamp
Browse files Browse the repository at this point in the history
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
  • Loading branch information
b1rger committed May 7, 2024
1 parent fb361b1 commit ca5bf94
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
3 changes: 3 additions & 0 deletions apis_core/history/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@

class HistoryConfig(AppConfig):
name = "apis_core.history"

def ready(self):
from . import signals # noqa: F401
5 changes: 0 additions & 5 deletions apis_core/history/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
9 changes: 9 additions & 0 deletions apis_core/history/signals.py
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit ca5bf94

Please sign in to comment.