This package lets you use real Python (PEP435-style) enums with Django.
django-enumfields2
is a friendly drop-in fork of hzdg/django-enumfields
that's still maintained.
pip install django-enumfields2
from enumfields import EnumField
from enum import Enum
class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'
class MyModel(models.Model):
color = EnumField(Color, max_length=1)
Elsewhere:
m = MyModel.objects.filter(color=Color.RED)
EnumIntegerField
works identically, but the underlying storage mechanism is
an IntegerField
instead of a CharField
.
Call the formfield
method to use an EnumField
directly in a Form
.
class MyForm(forms.Form):
color = EnumField(Color, max_length=1).formfield()
Normally, you just use normal PEP435-style enums, however, django-enumfields also includes its own version of Enum with a few extra bells and whistles. Namely, the smart definition of labels which are used, for example, in admin dropdowns. By default, it will create labels by title-casing your constant names. You can provide custom labels with a nested "Labels" class.
from enumfields import EnumField, Enum # Our own Enum class
class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'
class Labels:
RED = 'A custom label'
class MyModel(models.Model):
color = EnumField(Color, max_length=1)
assert Color.GREEN.label == 'Green'
assert Color.RED.label == 'A custom label'
enumfields.admin.EnumFieldListFilter
is provided to allow using enums in
list_filter
.
from enumfields.admin import EnumFieldListFilter
class MyModelAdmin(admin.ModelAdmin):
list_filter = [('color', EnumFieldListFilter)]
EnumSupportSerializerMixin
mixin allows you to use enums in DRF serializers.
# models.py
from enumfields import EnumField
from enum import Enum
class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'
class MyModel(models.Model):
color = EnumField(Color, max_length=1)
# serializers.py
from enumfields.drf.serializers import EnumSupportSerializerMixin
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(EnumSupportSerializerMixin, serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'