Skip to content

Instantly share code, notes, and snippets.

@cypreess
Created July 11, 2018 08:18
Show Gist options
  • Save cypreess/c9d2a1160d701ac87fed4b383d9fab3d to your computer and use it in GitHub Desktop.
Save cypreess/c9d2a1160d701ac87fed4b383d9fab3d to your computer and use it in GitHub Desktop.
Django choices helper class
# Example usage:
# class Car(models.Model):
# class Colors(ChoiceEnum):
# RED = 'red'
# WHITE = 'white'
# BLUE = 'blue'
#
# color = models.CharField(max_length=5, choices=Colors.choices(), default=Colors.RED)
#
# Querying requires an extra word to type though...
# red_cars = Car.objects.filter(color=Car.Colors.RED.value)
from enum import Enum
class ChoiceEnum(Enum):
@classmethod
def choices(cls):
return tuple((x.name, x.value) for x in cls)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment