Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from django.db import models
4from django.utils.translation import ugettext_lazy as _
5from superdjango.shortcuts import there_can_be_only_one
7# Exports
9__all__ = (
10 "PrimaryMixin",
11)
13# Constants
15# Models
18class PrimaryMixin(models.Model):
19 """Base class for implementing a "primary" model.
21 This model supplies the methods for using the ``pre_save`` signal and to acquire the name of the field that provides
22 the primary flag.
24 """
26 class Meta:
27 abstract = True
29 @staticmethod
30 def allow_one_primary(sender, **kwargs):
31 """Use this when there can be only one ``is_primary`` that is ``True``. See ``allow_one_default`` for
32 implementation example.
33 """
34 instance = kwargs['instance']
35 primary_flag = instance.get_primary_flag_name()
37 # noinspection PyTypeChecker
38 there_can_be_only_one(sender, instance, primary_flag)
40 @classmethod
41 def get_primary_flag_name(cls):
42 """Get the name of the field that is used to mark the record as primary.
44 :rtype: str
46 """
47 return "is_primary"
49 @staticmethod
50 def require_one_primary(sender, **kwargs):
51 """Works like ``allow_one_primary()`` but also insures that the first record entered becomes the primary."""
52 # noinspection PyTypeChecker
53 instance = kwargs['instance']
54 primary_flag = instance.get_primary_flag_name()
56 is_primary = getattr(instance, primary_flag)
58 if not is_primary:
59 if sender.objects.filter(**{primary_flag: True}).count() == 0:
60 setattr(instance, primary_flag, True)
62 there_can_be_only_one(sender, instance, primary_flag)