You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

83 lines
2.2 KiB

from django.conf import settings
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.db import models
# Create your models here.
STATUS_NEW = 0
STATUS_ACTIVE = 25
STATUS_DELETED = 50
STATUS_DEFAULT = STATUS_NEW
STATUS_CHOICES = (
(STATUS_NEW, _('New')),
(STATUS_ACTIVE, _('Active')),
(STATUS_DELETED, _('Deleted')),
)
class ActualOnlyManager(models.Manager):
def get_queryset(self):
queryset = super().get_queryset()
if not settings.DEBUG:
queryset = queryset.exclude(status=STATUS_DELETED)
return queryset
class ActiveOnlyManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status=STATUS_ACTIVE)
class DeletedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status=STATUS_DELETED)
class AbstractDateTimeModel(models.Model):
create_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class AbstractStatusModel(AbstractDateTimeModel):
status = models.SmallIntegerField(default=STATUS_DEFAULT, choices=STATUS_CHOICES)
objects = ActualOnlyManager()
deleted = DeletedManager()
active = ActiveOnlyManager()
@property
def is_active(self):
return self.status == STATUS_ACTIVE
@is_active.setter
def is_active(self, value):
if value:
self.status = STATUS_ACTIVE
else:
self.status = STATUS_DEFAULT
def delete(self, using=None, keep_parents=False):
self.status = STATUS_DELETED
self.save(using=using)
def delete_from_base(self, using=None, keep_parents=False):
return super().delete(using, keep_parents)
class Meta:
abstract = True
class CaseInsensitiveQuerySet(models.QuerySet):
CASE_INSENSITIVE_FIELDS = ('email',)
def _filter_or_exclude(self, negate, *args, **kwargs):
for field in self.CASE_INSENSITIVE_FIELDS:
if field in kwargs:
kwargs[field + '__iexact'] = kwargs[field]
del kwargs[field]
return super()._filter_or_exclude(negate, *args, **kwargs)