How To add created_at, updated_at, deleted_at, and soft deletion functionality in Django

To add created_at, updated_at, deleted_at, and soft deletion functionality in Django, you can follow these steps:

  1. Import the necessary modules in your Django models file (models.py):

from django.db import models
from django.utils import timezone

  1. Add the following fields to your model class:

class YourModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(blank=True, null=True)

  • The created_at field will automatically set the current date and time when a new object is created.
  • The updated_at field will automatically update the date and time whenever the object is saved.
  • The deleted_at field is initially set to None, indicating that the object is not deleted. When an object is deleted, you can set this field to the current date and time.
  1. Create a custom model manager for soft deletions. This manager will handle retrieving only the non-deleted objects:

class YourModelManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(deleted_at__isnull=True) 
  1. Modify your model class to use the custom manager:

class YourModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    deleted_at = models.DateTimeField(blank=True, null=True)

    objects = YourModelManager()
    all_objects = models.Manager() # Includes all objects (including deleted ones)

  1. In the views or wherever you want to retrieve the objects, use YourModel.objects.all() to fetch only non-deleted objects. If you want to retrieve all objects (including deleted ones), use YourModel.all_objects.all().

  2. Optionally, you can override the delete() method in your model to perform a soft deletion instead of a hard deletion:


class YourModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    deleted_at = models.DateTimeField(blank=True, null=True)

    objects = YourModelManager()
    all_objects = models.Manager()

    def delete(self, using=None, keep_parents=False):
        self.deleted_at = timezone.now()
        self.save()
 
  • By overriding the delete() method, when you call your_object.delete(), it will set the deleted_at field to the current date and time, effectively soft deleting the object.

With these steps, you should be able to add created_at, updated_at, deleted_at, and soft deletion functionality to your Django models.

Comments

Leave a Reply