Django-SafeDelete: Soft Delete in Django Made Easy
Django is a powerful web framework that provides a robust set of features to build web applications.
However, one feature that is not built-in but is often required is "soft delete" functionality.
Soft delete allows you to mark records as deleted without actually removing them from the database.
This is where Django-SafeDelete comes into play.
Django-SafeDelete is a third-party package that makes implementing soft delete in Django models a breeze.
In this article, we'll explore what Django-SafeDelete is, why you might need it, and how to use it in your Django projects.
Package GitHub at: https://github.com/makinacorpus/django-safedelete
What is Soft Delete?
In a typical database operation, when you delete a record, it's gone forever.
However, there are many scenarios where you might want to keep the deleted records for auditing, historical data, or to easily undo the delete operation.
Soft delete allows you to mark a record as deleted without actually removing it from the database.
Why Django-SafeDelete?
While you can implement soft delete functionality manually by adding a is_deleted field to your models and overriding the QuerySet to filter out deleted records, this approach requires you to write a lot of custom code.
Django-SafeDelete provides a more straightforward and reusable way to implement soft delete.
Features
- Easy to integrate with existing Django models.
- Customizable deletion policies.
- Built-in support for undelete.
- QuerySet methods to easily filter soft-deleted objects.
Installation
Installing Django-SafeDelete is as simple as running a pip command:
pip install django-safedelete
How to Use Django-SafeDelete
Basic Usage
First, import SafeDeleteModel from safedelete.models:
from safedelete.models import SafeDeleteModelInstead of inheriting your model from models.Model, inherit it from SafeDeleteModel:
from django.db import models
from safedelete.models import SafeDeleteModel
class MyModel(SafeDeleteModel):
name = models.CharField(max_length=100)
Since you've modified the model, don't forget to create and apply migrations.
python manage.py makemigrations
python manage.py migrate
Customization
Django-SafeDelete allows you to customize the deletion behavior by setting the _safedelete_policy attribute on your model. The available policies are:
SOFT_DELETE: The default policy, which marks the object as deleted.SOFT_DELETE_CASCADE: Soft-deletes the object as well as related objects.HARD_DELETE: Actually deletes the object from the database.HARD_DELETE_NOCASCADE: Deletes the object but not related objects.