Source code for superdjango.db.expiration.managers

# Imports

from django.db import models
from django.utils.timezone import now

Q = models.Q

# Exports

__all__ = (
    "ExpirationManager",
    "ExpirationQuerySet",
    "ExpiredManager",
    "UnExpiredManager",
)

# QuerySets


[docs]class ExpirationQuerySet(models.QuerySet): """Works in conjunction with ``ExpirationModel`` to help filter out records that have expired. """
[docs] def expired(self): """Filter for records that have expired.""" query1 = Q(has_expired=True) query2 = Q(expiration_dt_lt=now()) return self.filter(query1 | query2)
[docs] def unexpired(self): """Filter for records that have not expired.""" query1 = Q(has_expired=True) query2 = Q(expiration_dt__gt=now()) return self.filter(~query1 | query2)
# Managers
[docs]class ExpirationManager(models.Manager): """Works in conjunction with ``ExpirationModel`` to filter by expiration. """
[docs] def expired(self): """Get records that have expired. :rtype: QuerySet """ return self.get_queryset().expired()
[docs] def expiry(self): """Update all expired records. .. warning:: This updates the database. """ current_dt = now() criteria = { 'expiration_dt__gt': current_dt, 'has_expired': False, } qs = self.get_queryset().filter(**criteria) qs.update(has_expired=True)
# noinspection PyMethodMayBeStatic
[docs] def get_queryset(self): """Provide custom queryset.""" return ExpirationQuerySet()
[docs] def unexpired(self): """Get records that have not yet expired.""" return self.get_queryset().unexpired()
[docs]class ExpiredManager(models.Manager): """Work only with expired records.""" # noinspection PyMethodMayBeStatic
[docs] def get_queryset(self): return ExpirationQuerySet().expired()
[docs]class UnExpiredManager(models.Manager): """Work only with unexpired records.""" # noinspection PyMethodMayBeStatic
[docs] def get_queryset(self): return ExpirationQuerySet().unexpired()