Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix choices in ChoiceField to support IntEnum #8955

Merged
merged 1 commit into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 6 additions & 11 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import re
import uuid
from collections.abc import Mapping
from enum import Enum

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
Expand All @@ -17,7 +18,6 @@
MinValueValidator, ProhibitNullCharactersValidator, RegexValidator,
URLValidator, ip_address_validators
)
from django.db.models import IntegerChoices, TextChoices
from django.forms import FilePathField as DjangoFilePathField
from django.forms import ImageField as DjangoImageField
from django.utils import timezone
Expand Down Expand Up @@ -1401,11 +1401,8 @@ def __init__(self, choices, **kwargs):
def to_internal_value(self, data):
if data == '' and self.allow_blank:
return ''

if isinstance(data, (IntegerChoices, TextChoices)) and str(data) != \
str(data.value):
if isinstance(data, Enum) and str(data) != str(data.value):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from the test failures it seems that Enum is not defined. you might forgot to import it? or could you check what is the issue?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, I have added the import statement now.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure why you are removing the django compatibility support codes here if isinstance(data, (IntegerChoices, TextChoices)) and str(data) !=
str(data.value):

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please add unit test coverage for the changes?

data = data.value

try:
return self.choice_strings_to_values[str(data)]
except KeyError:
Expand All @@ -1414,11 +1411,8 @@ def to_internal_value(self, data):
def to_representation(self, value):
if value in ('', None):
return value

if isinstance(value, (IntegerChoices, TextChoices)) and str(value) != \
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same goes for this. we are not going to remove django compatibility features.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I should make it clear.
if isinstance(value, (IntegerChoices, TextChoices)) and str(value) != \ in #8986 not resolve the problem, and this if judgment will never be executed with the IntegerChoices and TextChoices.
Because this problem only occurs in the python version little than 3.11 and use Enum as base class.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add if isinstance(data, Enum) and str(data) != str(data.value): just enhances the Enum support for python version little than 3.11.
if isinstance(value, (IntegerChoices, TextChoices)) and str(value) != \ has not effect when users use IntegerChoices or TextChoices, because str(value) always equal to value.value according to 8740ff334ae3e001514c42ac1fb63a5e4cfa5cd1, but user swill still meet the problem when they use Enum, because that if judgment not solve the problem of IntEnum in different python version.

str(value.value):
if isinstance(value, Enum) and str(value) != str(value.value):
b7wch marked this conversation as resolved.
Show resolved Hide resolved
value = value.value

return self.choice_strings_to_values.get(str(value), value)

def iter_options(self):
Expand All @@ -1442,8 +1436,7 @@ def _set_choices(self, choices):
# Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out.
self.choice_strings_to_values = {
str(key.value) if isinstance(key, (IntegerChoices, TextChoices))
and str(key) != str(key.value) else str(key): key for key in self.choices
str(key.value) if isinstance(key, Enum) and str(key) != str(key.value) else str(key): key for key in self.choices
}

choices = property(_get_choices, _set_choices)
Expand Down Expand Up @@ -1829,6 +1822,7 @@ class HiddenField(Field):
constraint on a pair of fields, as we need some way to include the date in
the validated data.
"""

def __init__(self, **kwargs):
assert 'default' in kwargs, 'default is a required argument.'
kwargs['write_only'] = True
Expand Down Expand Up @@ -1858,6 +1852,7 @@ class ExampleSerializer(Serializer):
def get_extra_info(self, obj):
return ... # Calculate some data to return.
"""

def __init__(self, method_name=None, **kwargs):
self.method_name = method_name
kwargs['source'] = '*'
Expand Down
25 changes: 25 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1875,6 +1875,31 @@ def test_edit_choices(self):
field.run_validation(2)
assert exc_info.value.detail == ['"2" is not a valid choice.']

def test_enum_integer_choices(self):
from enum import IntEnum

class ChoiceCase(IntEnum):
first = auto()
second = auto()
# Enum validate
choices = [
(ChoiceCase.first, "1"),
(ChoiceCase.second, "2")
]
field = serializers.ChoiceField(choices=choices)
assert field.run_validation(1) == 1
assert field.run_validation(ChoiceCase.first) == 1
assert field.run_validation("1") == 1
# Enum.value validate
choices = [
(ChoiceCase.first.value, "1"),
(ChoiceCase.second.value, "2")
]
field = serializers.ChoiceField(choices=choices)
assert field.run_validation(1) == 1
assert field.run_validation(ChoiceCase.first) == 1
assert field.run_validation("1") == 1

def test_integer_choices(self):
class ChoiceCase(IntegerChoices):
first = auto()
Expand Down
Loading