From 7239f572a35f576735b0a77832caebbe7a9df227 Mon Sep 17 00:00:00 2001 From: Jon Date: Thu, 13 Jun 2024 23:38:30 +0930 Subject: [PATCH] fix(core): on object delete remove history entries !25 fixes #54 --- app/core/mixin/history_save.py | 44 ++++++++++++++++++++- app/core/tests/test_history/test_history.py | 9 +++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/app/core/mixin/history_save.py b/app/core/mixin/history_save.py index c5820b17..85373c4d 100644 --- a/app/core/mixin/history_save.py +++ b/app/core/mixin/history_save.py @@ -155,6 +155,38 @@ def save(self, *args, **kwargs): self.save_history(before, after) + def delete_history(self, item_pk, item_class): + """ Delete the objects history + + When an object is no longer in the database, delete the objects history and + that of the child objects. Only caveat is that if the history has a parent_pk + the object history is not to be deleted. + + Args: + item_pk (int): Primary key of the object to be deleted + item_class (str): Object class of the object to be deleted + """ + + object_history = History.objects.filter( + item_pk = item_pk, + item_class = item_class, + item_parent_pk = None, + ) + + if object_history.exists(): + + object_history.delete() + + child_object_history = History.objects.filter( + item_parent_pk = item_pk, + item_parent_class = item_class, + ) + + if child_object_history.exists(): + + child_object_history.delete() + + def delete(self, using=None, keep_parents=False): """ OverRides delete for keeping model history and on parent object ONLY!. @@ -162,16 +194,26 @@ def delete(self, using=None, keep_parents=False): """ before = {} + item_pk = self.pk + item_class = self._meta.model_name try: + before = self.__class__.objects.get(pk=self.pk).__dict__.copy() + except Exception: + pass - # Process the save + # Process the delete super().delete(using=using, keep_parents=keep_parents) after = self.__dict__.copy() if hasattr(self, 'parent_object'): + self.save_history(before, after) + + else: + + self.delete_history(item_pk, item_class) diff --git a/app/core/tests/test_history/test_history.py b/app/core/tests/test_history/test_history.py index f3526e90..207fcb97 100644 --- a/app/core/tests/test_history/test_history.py +++ b/app/core/tests/test_history/test_history.py @@ -53,3 +53,12 @@ def test_history_delete_calls_save_history(): This method saves the delete history to the database for parent objects """ pass + + + @pytest.mark.skip(reason="to be written") + def test_history_delete_calls_delete_history(): + """ During model delete, self.delete_history is called + + This method deletes the item and child-item history from the database + """ + pass