mirror of https://github.com/django/django.git
[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 dbcd7b064e
from master
This commit is contained in:
parent
495cdd6add
commit
8740ff334a
|
@ -60,7 +60,13 @@ class ChoicesMeta(enum.EnumMeta):
|
||||||
|
|
||||||
class Choices(enum.Enum, metaclass=ChoicesMeta):
|
class Choices(enum.Enum, metaclass=ChoicesMeta):
|
||||||
"""Class for creating enumerated choices."""
|
"""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):
|
class IntegerChoices(int, Choices):
|
||||||
|
|
|
@ -143,6 +143,12 @@ class ChoicesTests(SimpleTestCase):
|
||||||
APPLE = 1, 'Apple'
|
APPLE = 1, 'Apple'
|
||||||
PINEAPPLE = 1, 'Pineapple'
|
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):
|
class Separator(bytes, models.Choices):
|
||||||
FS = b'\x1c', 'File Separator'
|
FS = b'\x1c', 'File Separator'
|
||||||
|
|
Loading…
Reference in New Issue