10
10
from .compat import import_string
11
11
from .forms import EnumChoiceField
12
12
13
- metaclass = models .SubfieldBase if django .VERSION < (1 , 8 ) else type
14
13
14
+ class CastOnAssignDescriptor (object ):
15
+ """
16
+ A property descriptor which ensures that `field.to_python()` is called on _every_ assignment to the field.
15
17
16
- class EnumFieldMixin (six .with_metaclass (metaclass )):
18
+ This used to be provided by the `django.db.models.subclassing.Creator` class, which in turn
19
+ was used by the deprecated-in-Django-1.10 `SubfieldBase` class, hence the reimplementation here.
20
+ """
21
+
22
+ def __init__ (self , field ):
23
+ self .field = field
24
+
25
+ def __get__ (self , obj , type = None ):
26
+ if obj is None :
27
+ return self
28
+ return obj .__dict__ [self .field .name ]
29
+
30
+ def __set__ (self , obj , value ):
31
+ obj .__dict__ [self .field .name ] = self .field .to_python (value )
32
+
33
+
34
+ class EnumFieldMixin (object ):
17
35
def __init__ (self , enum , ** options ):
18
36
if isinstance (enum , six .string_types ):
19
37
self .enum = import_string (enum )
@@ -25,6 +43,10 @@ def __init__(self, enum, **options):
25
43
26
44
super (EnumFieldMixin , self ).__init__ (** options )
27
45
46
+ def contribute_to_class (self , cls , name ):
47
+ super (EnumFieldMixin , self ).contribute_to_class (cls , name )
48
+ setattr (cls , name , CastOnAssignDescriptor (self ))
49
+
28
50
def to_python (self , value ):
29
51
if value is None or value == '' :
30
52
return None
0 commit comments