Skip to content

Commit 8e84a9f

Browse files
author
David Sanders
committed
Allow invalid outputs to pass through to_representation() for ChoiceField & MultipleChoiceField
1 parent 6add1ac commit 8e84a9f

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

rest_framework/fields.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1042,10 +1042,16 @@ def to_internal_value(self, data):
10421042
except KeyError:
10431043
self.fail('invalid_choice', input=data)
10441044

1045+
def representation_value(self, value):
1046+
try:
1047+
return self.choice_strings_to_values[six.text_type(value)]
1048+
except KeyError:
1049+
return value
1050+
10451051
def to_representation(self, value):
10461052
if value in ('', None):
10471053
return value
1048-
return self.choice_strings_to_values[six.text_type(value)]
1054+
return self.representation_value(value)
10491055

10501056

10511057
class MultipleChoiceField(ChoiceField):
@@ -1073,7 +1079,7 @@ def to_internal_value(self, data):
10731079

10741080
def to_representation(self, value):
10751081
return set([
1076-
self.choice_strings_to_values[six.text_type(item)] for item in value
1082+
self.representation_value(item) for item in value
10771083
])
10781084

10791085

tests/test_fields.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -920,7 +920,8 @@ class TestChoiceField(FieldValues):
920920
}
921921
outputs = {
922922
'good': 'good',
923-
'': ''
923+
'': '',
924+
'amazing': 'amazing',
924925
}
925926
field = serializers.ChoiceField(
926927
choices=[
@@ -1005,7 +1006,7 @@ class TestMultipleChoiceField(FieldValues):
10051006
('aircon', 'incorrect'): ['"incorrect" is not a valid choice.']
10061007
}
10071008
outputs = [
1008-
(['aircon', 'manual'], set(['aircon', 'manual']))
1009+
(['aircon', 'manual', 'incorrect'], set(['aircon', 'manual', 'incorrect']))
10091010
]
10101011
field = serializers.MultipleChoiceField(
10111012
choices=[

0 commit comments

Comments
 (0)