base_models.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from django.db import models
  2. class CreatedModel(models.Model):
  3. created = models.DateTimeField(auto_now_add=True, db_index=True)
  4. class Meta:
  5. abstract = True
  6. class SoftDeleteManager(models.Manager):
  7. def __init__(self, is_deleted=False):
  8. super().__init__()
  9. self.is_deleted = is_deleted
  10. def get_queryset(self):
  11. return models.QuerySet(self.model, using=self._db).filter(
  12. is_deleted=self.is_deleted
  13. )
  14. class SoftDeleteModel(models.Model):
  15. """Based on https://tomisin.dev/blog/implementing-soft-delete-in-django-an-intuitive-guide"""
  16. is_deleted = models.BooleanField(default=False)
  17. objects = models.Manager()
  18. undeleted_objects = SoftDeleteManager()
  19. marked_for_deletion = SoftDeleteManager(is_deleted=True)
  20. class Meta:
  21. abstract = True
  22. def delete(self, *args, **kwargs):
  23. """Mark the record as deleted instead of deleting it"""
  24. self.is_deleted = True
  25. self.save()
  26. def force_delete(self, *args, **kwargs):
  27. """Delete the record from the database"""
  28. super().delete(*args, **kwargs)