Last active
April 28, 2018 04:50
-
-
Save santoshpy/aa1772c2c65f96cd33908adbf0f3dee6 to your computer and use it in GitHub Desktop.
Choices for Choices in Django CharFields
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
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) |
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
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