Skip to content

Commit 6a5da99

Browse files
committed
add serializer field management
1 parent 65f8d46 commit 6a5da99

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

elastic_framework/core/serializer.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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]

0 commit comments

Comments
 (0)