base_models.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from django.db import models
  2. from psqlextra.models import PostgresPartitionedModel
  3. from psqlextra.types import PostgresPartitioningMethod
  4. class CreatedModel(models.Model):
  5. created = models.DateTimeField(auto_now_add=True, db_index=True)
  6. class Meta:
  7. abstract = True
  8. class SoftDeleteManager(models.Manager):
  9. def __init__(self, is_deleted=False):
  10. super().__init__()
  11. self.is_deleted = is_deleted
  12. def get_queryset(self):
  13. return models.QuerySet(self.model, using=self._db).filter(
  14. is_deleted=self.is_deleted
  15. )
  16. class SoftDeleteModel(models.Model):
  17. """Based on https://tomisin.dev/blog/implementing-soft-delete-in-django-an-intuitive-guide"""
  18. is_deleted = models.BooleanField(default=False)
  19. objects = models.Manager()
  20. undeleted_objects = SoftDeleteManager()
  21. marked_for_deletion = SoftDeleteManager(is_deleted=True)
  22. class Meta:
  23. abstract = True
  24. def delete(self, *args, **kwargs):
  25. """Mark the record as deleted instead of deleting it"""
  26. self.is_deleted = True
  27. self.save()
  28. def force_delete(self, *args, **kwargs):
  29. """Delete the record from the database"""
  30. super().delete(*args, **kwargs)
  31. class AggregationModel(PostgresPartitionedModel, models.Model):
  32. """
  33. Partitioned base model for storing aggregate statistics in such as per
  34. time delta counts of events
  35. """
  36. date = models.DateTimeField()
  37. count = models.PositiveIntegerField()
  38. class Meta:
  39. abstract = True
  40. class PartitioningMeta:
  41. method = PostgresPartitioningMethod.RANGE
  42. key = ["date"]