Move common behaviors and querysets to Core.

This commit is contained in:
Josh Washburne 2018-03-29 12:13:38 -04:00
parent 3b62bc7b03
commit b927bd5bc0
2 changed files with 91 additions and 0 deletions

View file

@ -3,6 +3,65 @@ from django.utils import timezone
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
class Disableable(models.Model):
"""
Mixin for models that can be disabled with a specified reason.
"""
disabled = models.BooleanField(_('disabled state'), default=False)
disabled_date = models.DateTimeField(_('disabled on'),
default=None,
blank=True,
null=True)
disabled_reason = models.TextField(_('reason for disabling'), blank=True)
class Meta:
abstract = True
def disable(self, reason=''):
self.disabled = True
self.disabled_date = timezone.now()
self.disabled_reason = reason
self.save()
def enable(self):
self.disabled = False
self.disabled_date = None
self.disabled_reason = ''
self.save()
def _is_enabled(self):
return not self.disabled
_is_enabled.boolean = True
is_enabled = property(_is_enabled)
class Publishable(models.Model):
"""
Mixin for models that can be published to restrict accessibility before an
appointed date/time.
"""
published_date = models.DateTimeField(_('published for listening'),
default=None,
blank=True,
null=True)
class Meta:
abstract = True
def publish(self, date=None):
if date is None:
date = timezone.now()
self.published_date = date
self.save()
def _is_published(self):
if self.published_date is not None:
return self.published_date < timezone.now()
return False
_is_published.boolean = True
is_published = property(_is_published)
class Timestampable(models.Model): class Timestampable(models.Model):
""" """
Mixin for keeping track of when an object was created and last modified. Mixin for keeping track of when an object was created and last modified.

View file

@ -0,0 +1,32 @@
from django.db import models
from django.utils import timezone
class EnabledQuerySet(models.QuerySet):
"""
Queryset to select all objects that are enabled or not.
"""
def enabled(self):
return self.filter(disabled=False)
def disabled(self):
return self.filter(disabled=True)
class PublishedQuerySet(models.QuerySet):
"""
Queryset to select all objects that have been published or not.
"""
def published(self):
results = self.filter(
models.Q(published_date__isnull=False) &
models.Q(published_date__lte=timezone.now())
)
return results
def unpublished(self):
results = self.filter(
models.Q(published_date__isnull=True) |
models.Q(published_date__gte=timezone.now())
)
return results