Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django & Soft Deletion: Implementation architecture

Definitions

  • SOFT DELETE - does not remove an object from the database, but appears to do so
  • HARD DELETE - removes the object completely from the database

Question

What is the best way to implement soft deletion in a codebase (specifically, a Django project)?

The simplest method I think would be to simply add:

is_deleted = models.BooleanField(default=False)

to a superclass which implements a softDeleteObject, and then override delete() to set the appropriate flags on the objects in question. Related objects would also need to inherit from the same superclass.

An alternative would be instead to delete the original, and have what amounts to an Archive object which is a representation of the deleted objects.

Analysis

The first appears to have a greater degree of simplicity, but does require some wide-ranging overrides - for example, User would have to be overridden to ensure that the foreign key relations of all deleted objects still held, and that deleting a User then didn't hard delete all their soft-deleted objects.

The second could be implemented with pre_delete signals which trigger creation of the surrogate objects. This again has some advantages (don't need to override all the delete() methods), but does require the implementation of archived versions of the models used in the project.

Which is preferable, and are there other alternatives?

like image 984
jvc26 Avatar asked Feb 19 '13 12:02

jvc26


1 Answers

Why not to use active/deleted/status flags on the specific models where it is needed and do it this way? Or check the app django-reversion, there is probably everything you will need ;)

like image 170
Bruce Avatar answered Oct 11 '22 17:10

Bruce