How To

EnumField infers the primitive enumeration type and maps to the most appropriate Django field type. For example enum.StrEnum types would become CharField and enum.IntEnum types would become PositiveSmallIntegerField or PositiveIntegerField depending on the maximum enumeration value.

This means that EnumField columns will behave as expected and integrate broadly with third party libraries. When issues arise it tends to be because the primitive type was marshalled into an enum.Enum instance. Integrate with … with some popular third party libraries are provided.

For example:

from django.db import models
from django_enum import EnumField


class EquivalencyExample(models.Model):

    class TextEnum(models.TextChoices):

        VALUE0 = 'V0', 'Value 0'
        VALUE1 = 'V1', 'Value 1'
        VALUE2 = 'V2', 'Value 2'

    txt_enum = EnumField(TextEnum, null=True, blank=True, default=None)

    txt_choices = models.CharField(
        max_length=2,
        choices=TextEnum.choices,
        null=True,
        blank=True,
        default=None
    )

txt_enum and txt_choices fields are equivalent in all ways with the following exceptions:

EquivalencyExample.objects.create(txt_enum='V0', txt_choices='V0')

# txt_enum fields will always be an instance of the TextEnum type, unless
# set to a value that is not part of the enumeration

assert isinstance(
    EquivalencyExample.objects.first().txt_enum,
    EquivalencyExample.TextEnum
)
assert isinstance(
    EquivalencyExample.objects.first().txt_choices,
    str
)

# by default EnumFields are more strict, this is possible:
EquivalencyExample.objects.create(txt_choices='AA')

# but this will throw a ValueError (unless strict=False)
try:
    EquivalencyExample.objects.create(txt_enum='AA')
    assert False
except ValueError:
    assert True

# and this will throw a ValidationError
try:
    EquivalencyExample(txt_enum='AA').full_clean()
    assert False
except ValidationError:
    assert True

ModelForm classes, DRF serializers and filters will behave the same way with txt_enum and txt_choices. A few types are provided for deeper integration with forms and django-filter but their usage is optional. See Use Forms and django-filter.

Very rich enumeration fields that encapsulate much more functionality in a simple declarative syntax are possible with EnumField. See enum-properties.