Skip to content

Instantly share code, notes, and snippets.

@santoshpy
Last active April 28, 2018 04:50
Show Gist options
  • Save santoshpy/aa1772c2c65f96cd33908adbf0f3dee6 to your computer and use it in GitHub Desktop.
Save santoshpy/aa1772c2c65f96cd33908adbf0f3dee6 to your computer and use it in GitHub Desktop.
Choices for Choices in Django CharFields
from .utils import ChoiceEnum
class Car(models.Model):
# Encapsulation, we meet again.
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