File tree 1 file changed +36
-0
lines changed
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ ''' extension of DRF serializer
2
+
3
+ '''
4
+
5
+ from rest_framework .fields import ChoiceField
6
+
7
+
8
+ class DisplayFieldWithChoice (ChoiceField ):
9
+ ''' Used into serializer to display choiced field
10
+ This field has a model mapping so you can define it as writable too
11
+
12
+ '''
13
+
14
+ def __init__ (self , choices = (), * args , ** kwargs ):
15
+ super (DisplayFieldWithChoice , self ).\
16
+ __init__ (choices = choices , * args , ** kwargs )
17
+ # prepare dictionary with direct and reverted choices
18
+ self .revert = {
19
+ value : key for key , value in self .choices .items ()
20
+ }
21
+ self .forward = {
22
+ key : value for key , value in self .choices .items ()
23
+ }
24
+
25
+ def valid_value (self , value ):
26
+ return value in self .forward
27
+
28
+ def from_native (self , value ):
29
+ try :
30
+ return self .revert [value ]
31
+ except KeyError :
32
+ raise ValidationError ('{}: invalid value for choice field' .\
33
+ format (value ))
34
+
35
+ def to_native (self , value ):
36
+ return self .forward [value ]
You can’t perform that action at this time.
0 commit comments