Last active
December 30, 2015 00:09
-
-
Save FZambia/7747581 to your computer and use it in GitHub Desktop.
create choices in django using enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
usage: | |
Event.objects.create(type=Event.TYPES.CHAT_ADDED) | |
""" | |
def enum(*sequential, **named): | |
enums = dict(zip(sequential, range(len(sequential))), **named) | |
reverse = dict((value, key) for key, value in enums.iteritems()) | |
enums['reverse_mapping'] = reverse | |
return type('Enum', (), enums) | |
class Event(models.Model): | |
event_types = ( | |
"CHAT_ADDED", | |
"CHAT_CHANGED", | |
"CHAT_REMOVED", | |
) | |
TYPES = enum(*event_types) | |
TYPE_CHOICES = [(getattr(TYPES, x), TYPES.reverse_mapping[getattr(TYPES, x)]) for x in event_types] | |
type = models.IntegerField(choices=TYPE_CHOICES) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment