+class ChoiceField(serializers.CharField):
+ def __init__(self, *args, **kwargs):
+ sentinel = object()
+ self._choices = kwargs.pop('choices', sentinel)
+ if self._choices is sentinel:
+ raise Exception('Choices is required')
+ else:
+ self._choices = set(self._choices)
+ super().__init__(self, *args, **kwargs)
+
+ def to_internal_value(self, data):
+ if data not in choices:
+ raise serializers.ValidationError('{} not in choices {}'.format(
+ data,
+ self._choices,
+ ))
+ return data
+