Skip to content

Commit

Permalink
[3.0.x] Fixed #30902 -- Added __str__() for model choice enums.
Browse files Browse the repository at this point in the history
Allows expected behavior when cast to str, also matching behaviour of
created instances with those fetched from the DB.

Thanks to Simon Charette, Nick Pope, and Shai Berger for reviews.

Backport of dbcd7b0 from master
  • Loading branch information
carltongibson authored and felixxm committed Oct 25, 2019
1 parent 495cdd6 commit 8740ff3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 7 additions & 1 deletion django/db/models/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ def values(cls):

class Choices(enum.Enum, metaclass=ChoicesMeta):
"""Class for creating enumerated choices."""
pass

def __str__(self):
"""
Use value when cast to str, so that Choices set as model instance
attributes are rendered as expected in templates and similar contexts.
"""
return str(self.value)


class IntegerChoices(int, Choices):
Expand Down
6 changes: 6 additions & 0 deletions tests/model_enums/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ class Fruit(models.IntegerChoices):
APPLE = 1, 'Apple'
PINEAPPLE = 1, 'Pineapple'

def test_str(self):
for test in [Gender, Suit, YearInSchool, Vehicle]:
for member in test:
with self.subTest(member=member):
self.assertEqual(str(test[member.name]), str(member.value))


class Separator(bytes, models.Choices):
FS = b'\x1c', 'File Separator'
Expand Down

0 comments on commit 8740ff3

Please sign in to comment.