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, _('Новый')), (STATUS_ACTIVE, _('Активный')), (STATUS_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 # @TODO: translate into english and use translation 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)