Suppose that I have django models such A ->B ->C ->D in the default database.
C is a foreign key in D,similarly B in C and C in A.
On the deletion of the object A,the default behaviour of Django is that all the objects related to A directly or indirectly will get deleted automatically(On delete cascade).Thus, B,C,D would get automatically deleted.
I want to implement deletion in a way such that on deletion of an object of A it would get moved to another database named 'del'.Also along with it all other related objects of B,C,D will also get moved.
Is there an easy way of implementing this in one go?
Soft Delete Model This means that Django will not create a database table for it. Now, we can create our models as subclasses of SoftDeleteModel to grant them the ability to be soft-deleted. Let's take the example of a Note model. class Note(SoftDeleteModel): user = models. ForeignKey(User, on_delete=models.
And implementing soft delete is easy! You just add the “Is_Deleted” or “Delete_Date” column to your tables (or attributes to your Document) and replace all delete statement invocations in your application code to updates. And yes, you need to modify all retrieve statements to take into account this new attribute.
This is a set of small classes to make soft deletion of objects. Use the abstract model SoftDeleteModel for adding two new fields: is_deleted - is a boolean field, shows weather of a deletion state of object.
Hard vs soft deletesA “hard” delete is when rows are deleted using DELETE FROM table WHERE ... A “soft” delete is when rows are deleted using UPDATE table SET deleted_at = now() WHERE ...
I have implemented this thing using a deleted flag on each model of my database instead of moving things to separate database as follows:
deleted = models.BooleanField(default=False)
And defined a soft_del function for each model as follows:
def soft_del(self):
self.deleted = True
self.save()
So the deleted models would exist in the same database with deleted flag set to True.
Also to produce an ON DELETE CASCADE effect I have added such soft_del functions to each model and given a related_name to each foreign key in the model as follows:
class B(models.Model)
a = models.ForeignKey(A,related_name='related_Bs'))
and then call the soft_del of child when inside the soft_del of parent as follows:
def soft_del_A(self):
self.deleted = True
for b in A.related_Bs.all():
b.soft_del_B()
self.save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With