Skip to content

Instantly share code, notes, and snippets.

@FZambia
Last active December 30, 2015 00:09
Show Gist options
  • Save FZambia/7747581 to your computer and use it in GitHub Desktop.
Save FZambia/7747581 to your computer and use it in GitHub Desktop.
create choices in django using enums
"""
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