← Back to Django, page 5

django-0099 · Hard senior

How do you design soft deletion in Django with a default manager, a restore path and a partial unique constraint, and what are its limits?

Soft deletion marks rows with deleted_at instead of removing them. Use a default manager that hides deleted rows, an all_objects manager to see them, a queryset delete() that updates the marker, and a partial UniqueConstraint(condition=Q(deleted_at__isnull=True)) so deleted rows do not block re-using values such as an email. Limits: cascades, foreign keys, unique lookups, privacy requirements and table growth need explicit design.

Full answer

Why: undo, audit trails, and keeping references (old invoices pointing at a deleted student). Costs: every query must exclude deleted rows, uniqueness gets complicated and storage grows.

Building blocks:

python
class AliveQuerySet(models.QuerySet):
    def delete(self):                       # bulk soft delete
        return self.update(deleted_at=timezone.now())
    def alive(self): return self.filter(deleted_at__isnull=True)

class SoftDeleteModel(models.Model):
    deleted_at = models.DateTimeField(null=True, blank=True, db_index=True)
    objects = AliveManager()                 # default: hides deleted rows
    all_objects = models.Manager()           # includes deleted rows
    def delete(self, *a, **kw): self.deleted_at = timezone.now(); self.save(update_fields=["deleted_at"])
    def restore(self): self.deleted_at = None; self.save(update_fields=["deleted_at"])
    class Meta: abstract = True

Partial unique constraint: UniqueConstraint(fields=["roll_no"], condition=Q(deleted_at__isnull=True), name="uniq_alive_roll_no") enforces uniqueness among live rows only (supported by PostgreSQL and SQLite; MySQL needs another approach). Restoring a row whose value is now used by a live row violates the constraint, so restore code must handle IntegrityError.

Limits and decisions:

  • The first manager defined becomes _default_manager, used by related managers and the admin; Django's _base_manager (used for FK access and validation) is unfiltered by default, so mark.student still resolves to a deleted student.
  • Cascades: on_delete does nothing for soft deletes. Decide whether children are hidden too (a queryset filter through the relation, a post_save that cascades, or an explicit service).
  • bulk operations: QuerySet.update() bypasses save(), and raw SQL and joins ignore the manager.
  • Privacy laws (erasure requests) need real deletion or anonymisation; soft delete alone does not satisfy them.
  • Retention: purge old soft-deleted rows with a scheduled job.
  • Alternatives: an archive table, event sourcing, or database triggers.
  • Libraries such as django-safedelete package these patterns.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import IntegrityError, connection, models
from django.utils import timezone


class AliveQuerySet(models.QuerySet):
    def delete(self):
        return self.update(deleted_at=timezone.now())


class AliveManager(models.Manager.from_queryset(AliveQuerySet)):
    def get_queryset(self):
        return super().get_queryset().filter(deleted_at__isnull=True)


class Student(models.Model):
    roll_no = models.CharField(max_length=10)
    name = models.CharField(max_length=40)
    deleted_at = models.DateTimeField(null=True, blank=True)

    objects = AliveManager()
    all_objects = models.Manager.from_queryset(AliveQuerySet)()

    class Meta:
        app_label = "school"
        constraints = [models.UniqueConstraint(fields=["roll_no"], condition=models.Q(deleted_at__isnull=True),
                                               name="uniq_alive_roll_no")]

    def delete(self, *args, **kwargs):
        self.deleted_at = timezone.now()
        self.save(update_fields=["deleted_at"])

    def restore(self):
        self.deleted_at = None
        self.save(update_fields=["deleted_at"])


with connection.schema_editor() as editor:
    editor.create_model(Student)

asha = Student.objects.create(roll_no="BCA-1", name="Asha")
ravi = Student.objects.create(roll_no="BCA-2", name="Ravi")
asha.delete()
print("alive:", [s.name for s in Student.objects.order_by("id")], "| all rows:", Student.all_objects.count())

Student.objects.filter(name="Ravi").delete()                      # queryset delete is soft too
print("alive after queryset delete:", Student.objects.count(), "| all rows:", Student.all_objects.count())

Student.objects.create(roll_no="BCA-1", name="Asha (re-enrolled)")   # allowed: the old row is deleted
try:
    asha.restore()                                                   # the roll number is in use again
except IntegrityError:
    print("restore blocked by the partial unique constraint")
try:
    Student.objects.create(roll_no="BCA-1", name="Duplicate")
except IntegrityError:
    print("duplicate live roll_no rejected")

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Partial unique constraints work on SQLite and PostgreSQL; MySQL does not support conditional constraints. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): alive: ['Ravi'] | all rows: 2 alive after queryset delete: 0 | all rows: 2 restore blocked by the partial unique constraint duplicate live roll_no rejected

Key points

  • Hide deleted rows through the default manager; keep an all_objects manager
  • Override queryset delete() as well as instance delete()
  • Partial unique constraint scoped to live rows
  • Cascades, FK access and raw SQL need explicit handling
  • Soft delete does not meet erasure requirements

Common mistakes

  • Overriding instance delete() but not queryset delete()
  • Using a plain unique=True and blocking re-use of deleted values
  • Assuming foreign key access hides soft-deleted related rows
  • Treating soft delete as compliance with erasure requests
  • Forgetting a purge policy so tables grow forever

Follow-ups

  • How do you cascade soft deletes to related rows?
  • How does the admin interact with the default manager?
  • What are alternatives to soft delete?

Tips

  • Describe both managers
  • Explain the partial unique constraint
  • Mention cascades and privacy