Skip to content

Commit 8740ff3

Browse files
carltongibsonfelixxm
authored andcommitted
[3.0.x] Fixed #30902 -- Added __str__() for model choice enums.
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
1 parent 495cdd6 commit 8740ff3

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

django/db/models/enums.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,13 @@ def values(cls):
6060

6161
class Choices(enum.Enum, metaclass=ChoicesMeta):
6262
"""Class for creating enumerated choices."""
63-
pass
63+
64+
def __str__(self):
65+
"""
66+
Use value when cast to str, so that Choices set as model instance
67+
attributes are rendered as expected in templates and similar contexts.
68+
"""
69+
return str(self.value)
6470

6571

6672
class IntegerChoices(int, Choices):

tests/model_enums/tests.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,12 @@ class Fruit(models.IntegerChoices):
143143
APPLE = 1, 'Apple'
144144
PINEAPPLE = 1, 'Pineapple'
145145

146+
def test_str(self):
147+
for test in [Gender, Suit, YearInSchool, Vehicle]:
148+
for member in test:
149+
with self.subTest(member=member):
150+
self.assertEqual(str(test[member.name]), str(member.value))
151+
146152

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

0 commit comments

Comments
 (0)