Soft django delete database objects

Suppose I have django models such as A -> B -> C -> D in the default database.

C is the foreign key in D, similar to B in C and C in A.

When deleting an object A, the default behavior of Django is that all objects associated with A will directly or indirectly be deleted automatically (if the cascade is deleted). Thus, B, C, D are automatically deleted.

I want to implement the deletion in such a way that when deleting object A, it moves to another database with the name "del'.Also along with this, all other related objects B, C, D will also be moved.

Is there an easy way to implement this at a time?

+4
source share
3 answers

I implemented this thing using a remote flag for each model of my database, instead of moving things to a separate database as follows:

deleted = models.BooleanField(default=False)

And defined the soft_del function for each model as follows:

def soft_del(self):
        self.deleted = True            
        self.save()

Thus, remote models will exist in the same database with the remote flag set to True.

Also, to create the effect of ON DELETE CASCADE, I added such soft_del functions for each model and gave the associated 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 soft_del of the child when inside the soft_del of the parent:

def soft_del_A(self):
    self.deleted = True 
    for b in A.related_Bs.all():
        b.soft_del_B()

    self.save()
+4
source

delete A . - /.

0

There is a library that matches the default django removal style for soft hits. (i.e. uses Cascade parameters, do nothing, etc. from the model specification).

https://github.com/upgrad/django-deletes

PS: The library is still in beta, but active.

0
source

All Articles