Skip to content

Instantly share code, notes, and snippets.

@treyhunner
Created April 9, 2018 23:49
Show Gist options
  • Save treyhunner/fd2dc64efb50a147e0a29746862fe8fc to your computer and use it in GitHub Desktop.
Save treyhunner/fd2dc64efb50a147e0a29746862fe8fc to your computer and use it in GitHub Desktop.
Enum for use with Django ChoiceField
from enum import Enum, EnumMeta
class ChoiceEnumMeta(EnumMeta):
def __iter__(self):
return ((tag, tag.value) for tag in super().__iter__())
class ChoiceEnum(Enum, metaclass=ChoiceEnumMeta):
"""
Enum for Django ChoiceField use.
Usage::
class Colors(ChoiceEnum):
red = "Red"
green = "Green"
blue = "Blue"
class MyModel(models.Model):
color = models.CharField(max_length=20, choices=Colors)
"""
@waketzheng
Copy link

django-model-utils

https://github.com/jazzband/django-model-utils/blob/master/docs/utilities.rst

from model_utils import Choices

class Article(models.Model):
    STATUS = Choices('draft', 'published')
    status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20)

@freemansion
Copy link

freemansion commented Jul 30, 2018

@waketzheng, you're the man! thanks for pointing to django-model-utils

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment