Skip to content

Commit

Permalink
Don't mangle values when they're already enums.
Browse files Browse the repository at this point in the history
This breaks when you have two enum values with the same label.
  • Loading branch information
gavinwahl authored and akx committed Jun 16, 2016
1 parent dde117c commit d62e5de
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
2 changes: 2 additions & 0 deletions enumfields/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ def __init__(self, enum, **options):
def to_python(self, value):
if value is None or value == '':
return None
if isinstance(value, self.enum):
return value
for m in self.enum:
if value == m:
return m
Expand Down
12 changes: 12 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ class IntegerEnum(IntEnum):
class Labels:
A = 'foo'

class LabeledEnum(Enum):
FOO = 'foo'
BAR = 'bar'
FOOBAR = 'foobar'

class Labels:
FOO = 'Foo'
BAR = 'Bar'
# this is intentional. see test_nonunique_label
FOOBAR = 'Foo'

taste = EnumField(Taste, default=Taste.SWEET)
taste_null_default = EnumField(Taste, null=True, blank=True, default=None)
taste_int = EnumIntegerField(Taste, default=Taste.SWEET)
Expand All @@ -41,3 +52,4 @@ class Labels:
int_enum = EnumIntegerField(IntegerEnum, null=True, default=None, blank=True)

zero2 = EnumIntegerField(ZeroEnum, default=ZeroEnum.ZERO)
labeled_enum = EnumField(LabeledEnum, blank=True, null=True)
7 changes: 7 additions & 0 deletions tests/test_django_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,10 @@ def test_serialization():
fields = ser.getvalue()[0]["fields"]
assert fields["color"] == m.color.value
assert fields["taste"] == m.taste.value


def test_nonunique_label():
obj = MyModel(labeled_enum=MyModel.LabeledEnum.FOOBAR)

assert obj.labeled_enum is MyModel.LabeledEnum.FOOBAR

0 comments on commit d62e5de

Please sign in to comment.