python
42 lines · 10 steps
How soft deletes work in Django
A reusable abstract model that marks rows deleted with a timestamp instead of removing them.
Explained by
highlit
1from django.db import models
2from django.utils import timezone
3
4
5class SoftDeleteQuerySet(models.QuerySet):
6 def delete(self):
7 return super().update(deleted_at=timezone.now())
8
9 def hard_delete(self):
10 return super().delete()
11
12 def alive(self):
13 return self.filter(deleted_at__isnull=True)
14
15 def dead(self):
16 return self.filter(deleted_at__isnull=False)
17
18
19class SoftDeleteManager(models.Manager):
20 def get_queryset(self):
21 return SoftDeleteQuerySet(self.model, using=self._db).alive()
22
23
24class SoftDeleteModel(models.Model):
25 deleted_at = models.DateTimeField(null=True, blank=True, editable=False)
26
27 objects = SoftDeleteManager()
28 all_objects = SoftDeleteQuerySet.as_manager()
29
30 class Meta:
31 abstract = True
32
33 def delete(self, using=None, keep_parents=False):
34 self.deleted_at = timezone.now()
35 self.save(using=using, update_fields=["deleted_at"])
36
37 def hard_delete(self, using=None, keep_parents=False):
38 super().delete(using=using, keep_parents=keep_parents)
39
40 def restore(self):
41 self.deleted_at = None
42 self.save(update_fields=["deleted_at"])
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Overriding delete to set a timestamp keeps rows recoverable while hiding them from normal queries.
- 2A custom manager that filters in get_queryset makes soft-deleted rows invisible by default everywhere.
- 3Pairing a default manager with an unfiltered one lets you reach hidden rows when you genuinely need them.
Related explainers
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
Intermediate
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
python
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent
How a Django settings module is wired
configuration
environment-variables
middleware
Intermediate
8 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-soft-deletes-work-in-django-explained-python-bdb6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.