-
-
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) | |
""" |
@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:
class Order(models.Model):
class Status(ChoicesEnum):
DRAFT = 'Draft'
CONFIRMED = 'Confirmed'
PROCESSED = 'Processed'
CANCELED = 'Canceled'
status = models.CharField(max_length=16, choices=Status, default=Status.DRAFT, verbose_name='status')
After that I'm being able of doing:
Order.objects.filter(status=Order.Status.DRAFT).count()
The only two issues I faced were:
- I have to manually edit the migration and fix the default from
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). - When testing a DRF serializer I needed to str() the option to make it assert:
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!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you not get this error in Admin when editing?