Created
July 11, 2018 08:18
-
-
Save cypreess/c9d2a1160d701ac87fed4b383d9fab3d to your computer and use it in GitHub Desktop.
Django choices helper class
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
# 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