Source code for superdjango.db.primary.mixins

# Imports

from django.db import models
from django.utils.translation import ugettext_lazy as _
from superdjango.shortcuts import there_can_be_only_one

# Exports

__all__ = (
    "PrimaryMixin",
)

# Constants

# Models


[docs]class PrimaryMixin(models.Model): """Base class for implementing a "primary" model. This model supplies the methods for using the ``pre_save`` signal and to acquire the name of the field that provides the primary flag. """ class Meta: abstract = True
[docs] @staticmethod def allow_one_primary(sender, **kwargs): """Use this when there can be only one ``is_primary`` that is ``True``. See ``allow_one_default`` for implementation example. """ instance = kwargs['instance'] primary_flag = instance.get_primary_flag_name() # noinspection PyTypeChecker there_can_be_only_one(sender, instance, primary_flag)
[docs] @classmethod def get_primary_flag_name(cls): """Get the name of the field that is used to mark the record as primary. :rtype: str """ return "is_primary"
[docs] @staticmethod def require_one_primary(sender, **kwargs): """Works like ``allow_one_primary()`` but also insures that the first record entered becomes the primary.""" # noinspection PyTypeChecker instance = kwargs['instance'] primary_flag = instance.get_primary_flag_name() is_primary = getattr(instance, primary_flag) if not is_primary: if sender.objects.filter(**{primary_flag: True}).count() == 0: setattr(instance, primary_flag, True) there_can_be_only_one(sender, instance, primary_flag)