Fakultas Ilmu Komputer UI

Commit c9bfaedb authored by Dave Nathanael's avatar Dave Nathanael
Browse files

[REFACTOR] Add abstract base models and managers for rework

parent 20842e86
Pipeline #40878 failed with stages
in 1 minute and 46 seconds
from django.db import models
class SoftObjectManager(models.Manager):
class SoftDeleteManager(models.Manager):
def get_queryset(self, with_deleted=False):
if with_deleted:
return super().get_queryset()
return super().get_queryset().filter(deleted_at__isnull=True)
def all(self, with_deleted=False):
return self.get_queryset(with_deleted=with_deleted)
def deleted(self):
queryset = self.get_queryset(with_deleted=True)
return queryset.filter(deleted_at__isnull=False)
class SoftObjectManager(SoftDeleteManager):
def get_queryset(self, with_deleted=False):
if with_deleted:
return super().get_queryset()
......
import uuid
import pytz
from datetime import datetime
from django.db import models
from django.forms.models import model_to_dict
from apps.constants import (
TIMEZONE,
ACTIVITY_TYPE_CREATE,
ACTIVITY_TYPE_EDIT,
ACTIVITY_TYPE_DELETE
)
class BaseModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class SoftDeleteModel(BaseModel):
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
abstract = True
def delete(self):
if self.deleted_at is None:
self.deleted_at = datetime.now(tz=pytz.timezone(TIMEZONE))
self.save()
class HistoryEnabledModel(SoftDeleteModel):
class Meta:
abstract = True
def save(self, *args, **kwargs):
instance = super(HistoryEnabledModel, self).save(*args, **kwargs)
instance_dict = model_to_dict(self)
if instance_dict.get("id") is not None:
instance_dict.pop("id")
if instance_dict.get("created_at") is not None:
instance_dict.pop("created_at")
instance_dict.pop("deleted_at")
action = ACTIVITY_TYPE_CREATE if self._state.adding else ACTIVITY_TYPE_EDIT
instance_dict["object_id"] = self.id
instance_dict["action_type"] = action
self.history_class.objects.create(**instance_dict)
def delete(self):
instance = super(HistoryEnabledModel, self).delete()
instance_dict = model_to_dict(self)
if instance_dict.get("id") is not None:
instance_dict.pop("id")
if instance_dict.get("created_at") is not None:
instance_dict.pop("created_at")
instance_dict.pop("deleted_at")
instance_dict["object_id"] = self.id
instance_dict["action_type"] = ACTIVITY_TYPE_DELETE
if self.deleted_at is None:
self.history_class.objects.create(**instance_dict)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment