Skip to content

Commit 4520ba2

Browse files
committed
Support calling EnumField.to_representation() with choice key as value
1 parent ab59041 commit 4520ba2

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

rest_framework_dataclasses/fields.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ def to_internal_value(self, data):
3131
self.fail('invalid_choice', input=data)
3232

3333
def to_representation(self, value):
34+
# Some external libraries expect to be able to call to_representation() with the key from the choices
35+
# array, which seems at least somewhat reasonable. See #40.
36+
if not isinstance(value, self.enum_class):
37+
if value in self.choices:
38+
return value
39+
self.fail('invalid_choice', input=value)
40+
3441
if self.by_name:
3542
return value.name
3643
else:

tests/test_fields.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,7 @@ class Color(enum.Enum):
3636
self.assertEqual(field.to_representation(Color.GREEN), 'GREEN')
3737
with self.assertRaises(ValidationError):
3838
field.to_internal_value('FF0000')
39+
40+
self.assertEqual(field.to_representation('RED'), 'RED')
41+
with self.assertRaises(ValidationError):
42+
field.to_representation('FFFFFF')

0 commit comments

Comments
 (0)