Skip to content

Commit

Permalink
Support calling EnumField.to_representation() with choice key as value
Browse files Browse the repository at this point in the history
  • Loading branch information
oxan committed Jul 5, 2021
1 parent ab59041 commit 4520ba2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
7 changes: 7 additions & 0 deletions rest_framework_dataclasses/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ def to_internal_value(self, data):
self.fail('invalid_choice', input=data)

def to_representation(self, value):
# Some external libraries expect to be able to call to_representation() with the key from the choices
# array, which seems at least somewhat reasonable. See #40.
if not isinstance(value, self.enum_class):
if value in self.choices:
return value
self.fail('invalid_choice', input=value)

if self.by_name:
return value.name
else:
Expand Down
4 changes: 4 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,7 @@ class Color(enum.Enum):
self.assertEqual(field.to_representation(Color.GREEN), 'GREEN')
with self.assertRaises(ValidationError):
field.to_internal_value('FF0000')

self.assertEqual(field.to_representation('RED'), 'RED')
with self.assertRaises(ValidationError):
field.to_representation('FFFFFF')

0 comments on commit 4520ba2

Please sign in to comment.