diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 460645796a..96fcc257a2 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1045,7 +1045,7 @@ def to_internal_value(self, data): def to_representation(self, value): if value in ('', None): return value - return self.choice_strings_to_values[six.text_type(value)] + return self.choice_strings_to_values.get(six.text_type(value), value) class MultipleChoiceField(ChoiceField): @@ -1073,7 +1073,7 @@ def to_internal_value(self, data): def to_representation(self, value): return set([ - self.choice_strings_to_values[six.text_type(item)] for item in value + self.choice_strings_to_values.get(six.text_type(item), item) for item in value ]) diff --git a/tests/test_fields.py b/tests/test_fields.py index 1531fe2acf..55e9aacc11 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -920,7 +920,8 @@ class TestChoiceField(FieldValues): } outputs = { 'good': 'good', - '': '' + '': '', + 'amazing': 'amazing', } field = serializers.ChoiceField( choices=[ @@ -1005,7 +1006,7 @@ class TestMultipleChoiceField(FieldValues): ('aircon', 'incorrect'): ['"incorrect" is not a valid choice.'] } outputs = [ - (['aircon', 'manual'], set(['aircon', 'manual'])) + (['aircon', 'manual', 'incorrect'], set(['aircon', 'manual', 'incorrect'])) ] field = serializers.MultipleChoiceField( choices=[