Skip to content

Commit

Permalink
Merge pull request #125 from johnthagen/fix-str-representation
Browse files Browse the repository at this point in the history
Restore str representation conversion logic removed in 2.1.0
  • Loading branch information
akx authored Feb 23, 2021
2 parents f5eaf45 + 7164aa1 commit 2ce149e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
16 changes: 11 additions & 5 deletions enumfields/drf/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,17 @@ def __init__(self, enum, lenient=False, ints_as_names=False, **kwargs):
super().__init__(**kwargs)

def to_representation(self, instance):
assert isinstance(instance, self.enum), instance
if self.ints_as_names and isinstance(instance.value, int):
# If the enum value is an int, assume the name is more representative
return instance.name.lower()
return instance.value
if instance in ('', None):
return instance
try:
if not isinstance(instance, self.enum):
instance = self.enum(instance) # Try to cast it
if self.ints_as_names and isinstance(instance.value, int):
# If the enum value is an int, assume the name is more representative
return instance.name.lower()
return instance.value
except ValueError:
raise ValueError('Invalid value [{!r}] of enum {}'.format(instance, self.enum.__name__))

def to_internal_value(self, data):
if isinstance(data, self.enum):
Expand Down
4 changes: 2 additions & 2 deletions tests/enums.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.utils.translation import ugettext_lazy
from django.utils.translation import gettext_lazy

from enumfields import Enum, IntEnum

Expand All @@ -12,7 +12,7 @@ class Color(Enum):

class Labels:
RED = 'Reddish'
BLUE = ugettext_lazy('bluë')
BLUE = gettext_lazy('bluë')


class Taste(Enum):
Expand Down
17 changes: 17 additions & 0 deletions tests/test_serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import uuid

import pytest
from enumfields.drf import EnumField
from enumfields.drf.serializers import EnumSupportSerializerMixin
from rest_framework import serializers

Expand Down Expand Up @@ -42,6 +43,22 @@ def test_serialize(int_names):
assert data['int_enum'] == data['int_enum_not_editable'] == IntegerEnum.B.value


@pytest.mark.parametrize('instance, representation', [
('', ''),
(None, None),
('r', 'r'),
('g', 'g'),
('b', 'b'),
])
def test_enumfield_to_representation(instance, representation):
assert EnumField(Color).to_representation(instance) == representation


def test_invalid_enumfield_to_representation():
with pytest.raises(ValueError, match=r"Invalid value.*"):
assert EnumField(Color).to_representation('INVALID_ENUM_STRING')


@pytest.mark.django_db
@pytest.mark.parametrize('lenient_serializer', (False, True))
@pytest.mark.parametrize('lenient_data', (False, True))
Expand Down

0 comments on commit 2ce149e

Please sign in to comment.