Hide keyboard shortcuts

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 

2 

3from django.db import models 

4from django.utils.translation import ugettext_lazy as _ 

5from superdjango.shortcuts import there_can_be_only_one 

6 

7# Exports 

8 

9__all__ = ( 

10 "PrimaryMixin", 

11) 

12 

13# Constants 

14 

15# Models 

16 

17 

18class PrimaryMixin(models.Model): 

19 """Base class for implementing a "primary" model. 

20 

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. 

23 

24 """ 

25 

26 class Meta: 

27 abstract = True 

28 

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() 

36 

37 # noinspection PyTypeChecker 

38 there_can_be_only_one(sender, instance, primary_flag) 

39 

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. 

43 

44 :rtype: str 

45 

46 """ 

47 return "is_primary" 

48 

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() 

55 

56 is_primary = getattr(instance, primary_flag) 

57 

58 if not is_primary: 

59 if sender.objects.filter(**{primary_flag: True}).count() == 0: 

60 setattr(instance, primary_flag, True) 

61 

62 there_can_be_only_one(sender, instance, primary_flag)