Skip to content

Instantly share code, notes, and snippets.

@Cluas Cluas/choices_eunms.py
Last active Oct 25, 2018

Embed
What would you like to do?
Django model选项的优雅实现方式
from enum import Enum, EnumMeta
class ChoiceEnumMeta(EnumMeta):
def __iter__(self):
return ((tag.name, tag.value) for tag in super().__iter__())
class ChoiceEnum(Enum, metaclass=ChoiceEnumMeta): # Python3中的写法 python2使用__metaclass__
"""
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)
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.