High-Performance Soft Deletes in Django with Custom QuerySet Managers
Quick Answer: Implement audit-safe Django soft deletes with custom QuerySet managers, PostgreSQL partial unique indexes, and protected cascade deletion.
Production Django Soft-Delete Pattern: Implement audit-safe Django soft deletes using custom QuerySet managers, PostgreSQL partial unique indexes, and bulk delete. Learn how to implement audit-safe soft deletes in Django using custom models.QuerySet and models.Manager classes, handle bulk QuerySet.delete() overrides, and enforce uniqueness on active records using PostgreSQL partial unique indexes (UniqueConstraint(..., condition=Q(deleted_at__isnull=True))). Authored by Senior Backend Engineer Aldian Fazrihady.
In data-driven business applications, deleting records from the database is rarely a good idea. Accidental clicks can lead to catastrophic data loss, and hard-deleting records breaks historical audits and referential integrity. The industry standard is Soft Deletion—marking records as "deleted" via a timestamp column instead of actually removing the rows.
While there are several third-party Django libraries (like django-safedelete) that handle soft deletion, they often come with heavy overhead, buggy database migrations, and complex behaviors when performing cascading deletes or object serialization. In this post, we'll explore how to build a lightweight, bulletproof Soft Delete system from scratch using custom Django Managers and QuerySets.
The System Architecture: Three Simple Components
To build a native soft-delete system in Django, we need to customize three primary layers:
- Custom QuerySet: Ensures that bulk operations (like
.delete()and.restore()) update the timestamp column instead of dropping the rows. - Custom Managers: Defines how models query records by default (filtering out deleted items) while providing raw entry points for trash administration.
- Abstract Model: Serves as the base model containing the
deleted_attimestamp and overriding the defaultdelete()method. - ORM Compatibility: Overriding bulk
.delete()inside theQuerySetguarantees that bulk executions (e.g.Product.objects.filter(price__gt=100).delete()) perform soft deletions correctly. - Referential Integrity: Using an abstract class allows you to maintain foreign keys, avoiding complex database cascade configurations.
- Lightweight Footprint: Zero external third-party dependencies! This guarantees smooth database migrations and full compatibility with future Django versions.
- Senior Cloud Engineer Guide (AWS, GCP, Terraform IaC & FinOps)
- GCP Professional Cloud Architect Guide (Cloud Run, GKE & BigQuery)
- GCP Professional Data Engineer Guide (BigQuery, Dataflow & Pub/Sub)
- AI Application Engineer Guide (LLM Agents, RAG, MCP & LangGraph)
- Senior Full Stack Engineer Guide (React, Next.js, TypeScript & Python)
Step 1: Custom QuerySets and Managers
We'll create a SoftDeleteQuerySet that overrides the bulk .delete() call to execute an .update() statement. We'll also define a DeletedObjectQuerySet with a custom .restore() utility:
from django.db import models
from django.utils.timezone import now
class SoftDeleteQuerySet(models.QuerySet):
def delete(self):
# Override bulk delete to set timestamp
return self.update(deleted_at=now())
class DeletedObjectQuerySet(models.QuerySet):
def restore(self):
# Bulk restore
return self.update(deleted_at=None)
class SoftDeleteManager(models.Manager):
def get_queryset(self):
# Default manager only queries active records
return SoftDeleteQuerySet(self.model, using=self._db).filter(deleted_at__isnull=True)
class DeletedObjectManager(models.Manager):
def get_queryset(self):
# Queries ONLY deleted items (the trash bin)
return DeletedObjectQuerySet(self.model, using=self._db).filter(deleted_at__isnull=False)
Step 2: Building the Abstract Base Model
Next, we construct the abstract model. We define three managers: the default objects (active items only), deleted_objects (deleted items), and all_objects (a raw, unfiltered manager representing the entire physical table):
class SoftDeleteModel(models.Model):
deleted_at = models.DateTimeField(blank=True, null=True, default=None)
# Register custom managers
objects = SoftDeleteManager()
deleted_objects = DeletedObjectManager()
all_objects = models.Manager() # Native raw manager
class Meta:
abstract = True
def delete(self, *args, **kwargs):
# Single instance soft delete
self.deleted_at = now()
self.save(update_fields=['deleted_at'])
def restore(self):
# Restore instance
self.deleted_at = None
self.save(update_fields=['deleted_at'])
@property
def is_deleted(self):
return self.deleted_at is not None
Step 3: Integrating Soft Deletes in Your Code
Using the soft-delete model is incredibly simple. Just inherit from SoftDeleteModel when writing your tables, and Django handles the filtering transparently:
class Product(SoftDeleteModel):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
# Queries:
# 1. Fetching active products (automatically excludes deleted ones)
active_products = Product.objects.all()
# 2. Soft-deleting a product
product = Product.objects.first()
product.delete() # Simply sets product.deleted_at = now()
# 3. Viewing the trash bin
trash_bin = Product.deleted_objects.all()
# 4. Restoring a product
deleted_product = Product.deleted_objects.first()
deleted_product.restore() # Sets deleted_at = None
Key Implementation Advantages
Building your own soft-delete framework in Django requires less than 50 lines of clean Python code, providing a secure, performant, and maintainable trash bin system for your enterprise datasets.
Partial Unique Indexes (WHERE deleted_at IS NULL) for Django Soft-Delete Models
One of the most dangerous edge cases when implementing soft deletes in Django is unique constraint collisions. Standard Django unique=True fields (such as user emails or URL slugs) create a full database-level unique index across all rows. If a user deletes their account (setting deleted_at to a timestamp) and subsequently attempts to register again with the same email, PostgreSQL will reject the insertion with an IntegrityError because the soft-deleted row still occupies the unique index slot!
The modern, battle-tested solution in Django 4.2 and Django 5.0+ is using partial unique indexes via models.UniqueConstraint with a conditional Q(deleted_at__isnull=True) clause. This instructs PostgreSQL to enforce uniqueness strictly on active, non-deleted records while permitting arbitrary duplicates among soft-deleted historical records.
from django.db import models
from django.db.models import Q
class UserAccount(SoftDeleteModel):
email = models.EmailField(db_index=True)
username = models.CharField(max_length=50)
organization_id = models.IntegerField()
class Meta:
# Avoid standard unique=True on email to prevent soft-delete collisions!
constraints = [
models.UniqueConstraint(
fields=['email'],
condition=Q(deleted_at__isnull=True),
name='unique_active_user_email'
),
models.UniqueConstraint(
fields=['organization_id', 'username'],
condition=Q(deleted_at__isnull=True),
name='unique_active_org_username'
),
]
Under the hood, Django's database migration compiler emits clean, optimized PostgreSQL DDL:
CREATE UNIQUE INDEX "unique_active_user_email"
ON "app_useraccount" ("email")
WHERE ("deleted_at" IS NULL);
Handling Relational Cascades Safely
When implementing custom soft deletion without foreign key cascade support, avoid naive on_delete=models.CASCADE if child records should also be archived. Instead, use an explicit transactional archive worker or dispatch Django post-soft-delete signals that traverse reverse foreign key relationships in a single atomic database transaction.
Need High-Performance Django Architecture or Distributed Backend Scaling?
Whether designing zero-downtime database migrations, optimizing high-throughput PostgreSQL queries, or modernizing Python/Go microservices, explore the Senior Backend Engineer Guide & Technical Capabilities or book a focused sprint via the 1-Day Engineering & Problem Solving Service.
FAQ: PostgreSQL Partial Indexes & Django Soft Deletes
How much faster is a PostgreSQL partial index on deleted_at IS NULL? On a 10M-row table where 40% of rows are soft-deleted, CREATE INDEX CONCURRENTLY idx_active_email ON users(email) WHERE deleted_at IS NULL cuts index size by ~40% and keeps B-tree lookups under 1 ms without scanning tombstones.
How do you enforce unique constraints with soft deletes in Django? Use models.UniqueConstraint(fields=["email"], condition=Q(deleted_at__isnull=True), name="uniq_active_email") so re-registering a previously deleted account works cleanly while active rows stay strictly unique.
Explore Related Engineering Architecture Guides
PostgreSQL Partial Unique Index & Relational Cascade Safeguards
A common trap in Django soft-delete implementations happens when a deleted user or tenant record still occupies a global unique=True database index, blocking re-registration. Combine a PostgreSQL partial unique constraint with on_delete=models.PROTECT on financial ledger relations so deleted parent rows cannot bypass historical audit integrity:
from django.db import models
from django.db.models import Q
class TenantMember(models.Model):
tenant_id = models.UUIDField(db_index=True)
email = models.EmailField()
deleted_at = models.DateTimeField(null=True, blank=True, db_index=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["tenant_id", "email"],
condition=Q(deleted_at__isnull=True),
name="uniq_active_tenant_member_email",
)
]
Frequently Asked Questions: High-Performance Soft Deletes in Django
Why should Django soft-delete models use a PostgreSQL partial unique index instead of unique=True?
Standard unique=True constraints reject new rows even after an earlier record has deleted_at populated, preventing users from re-signing up with the same email or slug. A PostgreSQL partial UniqueConstraint with condition=Q(deleted_at__isnull=True) enforces uniqueness strictly among active rows and keeps the index smaller.
What happens during QuerySet.delete() when using a custom Django soft-delete manager?
Overriding QuerySet.delete() translates bulk deletes into an atomic UPDATE setting deleted_at=timezone.now() without bypassing database integrity checks or firing slow per-row Python signals across thousands of rows, while leaving a separate hard_delete() helper for GDPR erasure.
How do you inspect soft-deleted rows in Django Admin or audit scripts?
Attach a secondary unfiltered manager such as all_objects = models.Manager() alongside the default active objects manager so Django Admin, background archival tasks, and compliance exports can still query soft-deleted rows explicitly using Model.all_objects.all().
Should foreign keys pointing to soft-deletable Django models use CASCADE or PROTECT?
Financial, billing, and audit tables should use on_delete=models.PROTECT (or explicitly propagate soft-delete timestamps in a service transaction) rather than silent CASCADE so calling hard_delete() on a parent tenant never accidentally destroys historical invoice ledgers.