Skip to main content

Full and natural support for enumerations as Django model fields.

Project description

MIT license PyPI version fury.io PyPI pyversions PyPI djversions PyPI status Documentation Status Code Cov Test Status

Django Enum

Full and natural support for enumerations as Django model fields.

Many packages aim to ease usage of Python enumerations as model fields. Most were made obsolete when Django provided TextChoices and IntegerChoices types. The motivation for django-enum was to:

  • Always automatically coerce fields to instances of the Enum type.

  • Allow strict adherence to Enum values to be disabled.

  • Be compatible with Enum classes that do not derive from Django’s Choices.

  • Handle migrations appropriately. (See migrations)

  • Integrate as fully as possible with Django’s existing level of enum support.

  • Integrate with enum-properties to enable richer enumeration types.

  • Represent enum fields with the smallest possible column type.

  • Be as simple and light-weight an extension to core Django as possible.

django-enum works in concert with Django’s built in TextChoices and IntegerChoices to provide a new model field type, EnumField, that resolves the correct native Django field type for the given enumeration based on its value type and range. For example, IntegerChoices that contain values between 0 and 32767 become PositiveSmallIntegerField.

from django.db import models
from django_enum import EnumField

class MyModel(models.Model):

    class TextEnum(models.TextChoices):

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

    class IntEnum(models.IntegerChoices):

        ONE   = 1, 'One'
        TWO   = 2, 'Two',
        THREE = 3, 'Three'

    # this is equivalent to:
    #  CharField(max_length=2, choices=TextEnum.choices, null=True, blank=True)
    txt_enum = EnumField(TextEnum, null=True, blank=True)

    # this is equivalent to
    #  PositiveSmallIntegerField(choices=IntEnum.choices)
    int_enum = EnumField(IntEnum)

EnumField is more than just an alias. The fields are now assignable and accessible as their enumeration type rather than by-value:

instance = MyModel.objects.create(
    txt_enum=MyModel.TextEnum.VALUE1,
    int_enum=3  # by-value assignment also works
)

assert instance.txt_enum == MyModel.TextEnum('V1')
assert instance.txt_enum.label == 'Value 1'

assert instance.int_enum == MyModel.IntEnum['THREE']
assert instance.int_enum.value == 3

django-enum also provides IntegerChoices and TextChoices types that extend from enum-properties which makes possible very rich enumeration fields.

?> pip install enum-properties

from enum_properties import s
from django_enum import TextChoices  # use instead of Django's TextChoices
from django.db import models

class TextChoicesExample(models.Model):

    class Color(TextChoices, s('rgb'), s('hex', case_fold=True)):

        # name   value   label       rgb       hex
        RED     = 'R',   'Red',   (1, 0, 0), 'ff0000'
        GREEN   = 'G',   'Green', (0, 1, 0), '00ff00'
        BLUE    = 'B',   'Blue',  (0, 0, 1), '0000ff'

        # any named s() values in the Enum's inheritance become properties on
        # each value, and the enumeration value may be instantiated from the
        # property's value

    color = EnumField(Color)

instance = TextChoicesExample.objects.create(
    color=TextChoicesExample.Color('FF0000')
)
assert instance.color == TextChoicesExample.Color('Red')
assert instance.color == TextChoicesExample.Color('R')
assert instance.color == TextChoicesExample.Color((1, 0, 0))

# direct comparison to any symmetric value also works
assert instance.color == 'Red'
assert instance.color == 'R'
assert instance.color == (1, 0, 0)

# save by any symmetric value
instance.color = 'FF0000'

# access any enum property right from the model field
assert instance.color.hex == 'ff0000'

# this also works!
assert instance.color == 'ff0000'

# and so does this!
assert instance.color == 'FF0000'

instance.save()

# filtering works by any symmetric value or enum type instance
assert TextChoicesExample.objects.filter(
    color=TextChoicesExample.Color.RED
).first() == instance

assert TextChoicesExample.objects.filter(color=(1, 0, 0)).first() == instance

assert TextChoicesExample.objects.filter(color='FF0000').first() == instance

Please report bugs and discuss features on the issues page.

Contributions are encouraged!

Full documentation at read the docs.

Installation

  1. Clone django-enum from GitHub or install a release off PyPI :

pip install django-enum

Integrations are provided that leverage enum-properties to make enumerations do more work and to provide extended functionality for django-filter and djangorestframework.

pip install enum-properties
pip install django-filter
pip install djangorestframework

If features are utilized that require a missing optional dependency an exception will be thrown.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_enum-1.3.3.tar.gz (15.8 kB view details)

Uploaded Source

Built Distribution

django_enum-1.3.3-py3-none-any.whl (16.0 kB view details)

Uploaded Python 3

File details

Details for the file django_enum-1.3.3.tar.gz.

File metadata

  • Download URL: django_enum-1.3.3.tar.gz
  • Upload date:
  • Size: 15.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.11.4 Darwin/23.2.0

File hashes

Hashes for django_enum-1.3.3.tar.gz
Algorithm Hash digest
SHA256 6e5a1a19ceaffb8b728571ccf1c3aac9cfc224282677979fe040e3bcd941cbb7
MD5 f0fc9bfac20c4d4c1d19129c981eacf6
BLAKE2b-256 70a4ff45bc87ce10b4d08612f6197c8ec11934001e9b3bea1252084be421b606

See more details on using hashes here.

File details

Details for the file django_enum-1.3.3-py3-none-any.whl.

File metadata

  • Download URL: django_enum-1.3.3-py3-none-any.whl
  • Upload date:
  • Size: 16.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.11.4 Darwin/23.2.0

File hashes

Hashes for django_enum-1.3.3-py3-none-any.whl
Algorithm Hash digest
SHA256 9c3944a1ce39fa34e10c7e9c2e19b0a08a0100d4d81e7c84b40cf021605f74e0
MD5 f1e1b21f371efb56cf045ce0192d383a
BLAKE2b-256 98a75b44237a3806352114d98fb17140f33e8a7cdacc269257e53a2cc7125acc

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page