Skip to content

Commit 3ca5d08

Browse files
committed
Fix choices in ChoiceField to support IntEnum
Python support Enum in version 3.4, but changed __str__ to int.__str__ until version 3.11 to better support the replacement of existing constants use-case. [https://docs.python.org/3/library/enum.html#enum.IntEnum](https://docs.python.org/3/library/enum.html#enum.IntEnum) rest_frame work support Python 3.6+, this commit will support the Enum in choices of Field.
1 parent 38a74b4 commit 3ca5d08

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

rest_framework/fields.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1397,7 +1397,8 @@ def __init__(self, choices, **kwargs):
13971397
def to_internal_value(self, data):
13981398
if data == '' and self.allow_blank:
13991399
return ''
1400-
1400+
if isinstance(data, Enum) and str(data) != str(data.value):
1401+
data = data.value
14011402
try:
14021403
return self.choice_strings_to_values[str(data)]
14031404
except KeyError:
@@ -1406,6 +1407,8 @@ def to_internal_value(self, data):
14061407
def to_representation(self, value):
14071408
if value in ('', None):
14081409
return value
1410+
if isinstance(value, Enum) and str(value) != str(value.value):
1411+
value = value.value
14091412
return self.choice_strings_to_values.get(str(value), value)
14101413

14111414
def iter_options(self):
@@ -1429,7 +1432,7 @@ def _set_choices(self, choices):
14291432
# Allows us to deal with eg. integer choices while supporting either
14301433
# integer or string input, but still get the correct datatype out.
14311434
self.choice_strings_to_values = {
1432-
str(key): key for key in self.choices
1435+
str(key.value) if isinstance(key, Enum) and str(key) != str(key.value) else str(key): key for key in self.choices
14331436
}
14341437

14351438
choices = property(_get_choices, _set_choices)
@@ -1815,6 +1818,7 @@ class HiddenField(Field):
18151818
constraint on a pair of fields, as we need some way to include the date in
18161819
the validated data.
18171820
"""
1821+
18181822
def __init__(self, **kwargs):
18191823
assert 'default' in kwargs, 'default is a required argument.'
18201824
kwargs['write_only'] = True
@@ -1844,6 +1848,7 @@ class ExampleSerializer(Serializer):
18441848
def get_extra_info(self, obj):
18451849
return ... # Calculate some data to return.
18461850
"""
1851+
18471852
def __init__(self, method_name=None, **kwargs):
18481853
self.method_name = method_name
18491854
kwargs['source'] = '*'

0 commit comments

Comments
 (0)