Skip to content

Instantly share code, notes, and snippets.

@luto
Created August 8, 2019 14:12
Show Gist options
  • Save luto/d0c16e8ca3e8b5c3511eae54c9e69849 to your computer and use it in GitHub Desktop.
Save luto/d0c16e8ca3e8b5c3511eae54c9e69849 to your computer and use it in GitHub Desktop.
django model enum choices
from enum import Enum
class Choices(Enum):
"""
Helper to construct choices for django Model or Form fields.
class Animals(Choices):
DOG = 'dog'
CAT = 'cat'
class Vet(models.Model):
client = models.CharField(
choices=Animals.choices(),
max_length=Animals.max_length(),
default=Animals.DOG
)
"""
def __eq__(self, other):
if other is self:
return True
elif other == str(self):
# support asteroid.state == AsteroidState.DELETED
# (str from db) (actual enum value)
return True
else:
return False
@classmethod
def max_length(cls):
return max(len(c[0]) for c in cls.choices())
@classmethod
def choices(cls):
return ((str(c), c.value) for c in cls)
class Animals(Choices):
DOGGO = 'dog'
CATTO = 'cat'
CROCO = 'crocodile'
GIRAFFE = 'giraffe'
def test_choices_max_length():
assert Animals.max_length() == 15
def test_choices_choices():
assert list(Animals.choices()) == [
('Animals.DOGGO', 'dog'),
('Animals.CATTO', 'cat'),
('Animals.CROCO', 'crocodile'),
('Animals.GIRAFFE', 'giraffe'),
]
def test_choices_equality():
assert Animals.GIRAFFE == 'Animals.GIRAFFE'
assert Animals.GIRAFFE != 'Animals.CROCO'
assert Animals.GIRAFFE == Animals.GIRAFFE
assert Animals.GIRAFFE != Animals.CROCO
def test_choices_access():
assert str(Animals.GIRAFFE) in (c[0] for c in Animals.choices())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment