-
-
Save tadeo/0d3e94380353bb58451e0b5b72a9588f to your computer and use it in GitHub Desktop.
Enum for use with Django ChoiceField
This file contains hidden or 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, EnumMeta | |
class ChoicesEnumMeta(EnumMeta): | |
def __iter__(self): | |
return ((choice.name, choice.value) for choice in super().__iter__()) | |
class ChoicesEnum(Enum, metaclass=ChoicesEnumMeta): | |
def __str__(self): | |
return self.name | |
""" | |
Enum for Django ChoiceField use. | |
Usage: | |
class Colors(ChoicesEnum): | |
red = "Red" | |
green = "Green" | |
blue = "Blue" | |
class Car(models.Model): | |
color = models.CharField(max_length=20, choices=Colors) | |
red_cars = Car.objects.filter(color=Colors.RED) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nitrag I've just tried and I'm not having any issue. In my current implementation I nested the ChoicesEnum class inside the model class:
After that I'm being able of doing:
The only two issues I faced were:
oakfrog.orders.models.Status('Draft')
tooakfrog.orders.models.Order.Status('Draft')
(It seems that Django are not handling well the nested Class when doing the migration).self.assertEqual(data['status'], str(Order.Status.CONFIRMED))
. I suspect it's due DRAFT in the Enum is a symbolic name and the serializer is casting it to a plain string.I hope it helps!