django-enumfields

2.1.1 · active · verified Fri Apr 17

django-enumfields provides robust integration of Python's `enum.Enum` types with Django models, forms, and REST Framework serializers. It's currently at version 2.1.1 and follows a moderate release cadence, primarily focusing on Django and Python version compatibility and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

Define Python `enum.Enum` classes and use `EnumField`, `EnumIntegerField`, or `EnumCharField` in your Django models. The field stores the enum's value in the database and retrieves it as the enum instance.

import enum
from django.db import models
from enumfields import EnumField, EnumIntegerField, EnumCharField

class MyEnum(enum.Enum):
    FIRST = 1
    SECOND = 2
    THIRD = 3

class MyCharEnum(enum.Enum):
    FOO = 'foo'
    BAR = 'bar'

class MyModel(models.Model):
    # Stores the enum value as its internal integer value
    my_int_field = EnumIntegerField(MyEnum, default=MyEnum.FIRST)
    
    # Stores the enum value as its internal value (can be mixed types)
    my_field = EnumField(MyEnum, default=MyEnum.FIRST)
    
    # Stores the enum value as a string (requires max_length)
    my_char_field = EnumCharField(MyCharEnum, max_length=10, default=MyCharEnum.FOO)

    def __str__(self):
        return f'{self.my_int_field.name} - {self.my_char_field.value}'

# Example usage:
# instance = MyModel.objects.create(my_int_field=MyEnum.SECOND, my_char_field=MyCharEnum.BAR)
# print(instance.my_int_field) # MyEnum.SECOND
# print(instance.my_int_field.value) # 2
# print(instance.my_char_field.name) # FOO

view raw JSON →