diff --git a/enumfields/drf/fields.py b/enumfields/drf/fields.py index 6a7e864..bfac3c8 100644 --- a/enumfields/drf/fields.py +++ b/enumfields/drf/fields.py @@ -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): diff --git a/tests/enums.py b/tests/enums.py index 5b47276..40c8f69 100644 --- a/tests/enums.py +++ b/tests/enums.py @@ -1,4 +1,4 @@ -from django.utils.translation import ugettext_lazy +from django.utils.translation import gettext_lazy from enumfields import Enum, IntEnum @@ -12,7 +12,7 @@ class Color(Enum): class Labels: RED = 'Reddish' - BLUE = ugettext_lazy('bluë') + BLUE = gettext_lazy('bluë') class Taste(Enum): diff --git a/tests/test_serializers.py b/tests/test_serializers.py index 59236f8..cb132a4 100644 --- a/tests/test_serializers.py +++ b/tests/test_serializers.py @@ -1,6 +1,7 @@ import uuid import pytest +from enumfields.drf import EnumField from enumfields.drf.serializers import EnumSupportSerializerMixin from rest_framework import serializers @@ -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))