Skip to main content

A custom Django field able to use subclasses of Python's internal `Enum` class as choices

Project description

django-enum-choices

Library is still work in progress & unstable. When officially launched, we'll announce it.

A custom Django choice field to use with Python enums.

Installation

pip install django_enum_choices

Basic Usage

from django import models

from django_enum_choices.fields import EnumChoiceField


from enum import Enum

class FooBarEnumeration(Enum):
    FOO = 'foo'
    BAR = 'bar'


class MyModel(models.Model):
    foo_bar_field = EnumChoiceField(FooBarEnumeration)

Model creation

instance = MyModel.objects.create(foo_bar_field=FooBarEnumeration.BAR)

Changing enum values

instance.foo_bar_field = FooBarEnumeration.FOO
instance.save()

Filtering

MyModel.objects.filter(foo_bar_field=FooBarEnumeration.FOO)

Usage with Django Rest Framework

from rest_framework import serializers

from django_enum_choices.serializers import EnumChoiceField

class MyModelSerializer(serializers.ModelSerializer):
    foo_bar_field = EnumChoiceField(FooBarEnumeration)

    class Meta:
        model = MyModel
        fields = ('foo_bar_field', )

In python manage.py shell:

In [1]: instance = MyModel.objects.create(foo_bar_field=FooBarEnumeration.BAR)
In [2]: MyModelSerializer(instance).data
Out[2]: {'foo_bar_field': 'bar'}

Caveat

If you don't explicitly specify the foo_bar_field = EnumChoiceField(FooBarEnumeration), then you need to include the EnumChoiceModelSerializerMixin:

from rest_framework import serializers

from django_enum_choices.serializers import EnumChoiceModelSerializerMixin

class MyModelSerializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('foo_bar_field', )

By default ModelSerializer.build_standard_field coerces any field that has a model field with choices to ChoiceField wich returns the value directly.

Since enum values resemble EnumClass.ENUM_INSTANCE they won't be able to be encoded by the JSONEncoder when being passed to a Response.

That's why we need the mixin.

Implementation details

  • EnumChoiceField is a subclass of CharField.
  • Only subclasses of Enum are valid arguments for EnumChoiceField.
  • choices are generated from the values of the enumeration, like (str(value), str(value)), meaning you can put any valid Python object there.
  • max_length, if passed, is ignored. max_length is automatically calculated from the longest choice.

For example, lets have the following case:

class Value:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)


class Enumeration(Enum):
    A = Value(1)
    B = Value('foo')


class SomeModel(models.Model):
    enumeration = EnumChoiceField(Enumeration)

We'll have the following:

  • SomeModel.enumeration.choices == (('1', '1'), ('foo', 'foo'))
  • SomeModel.enumeration.max_length == 3

Development

git clone https://github.com/HackSoftware/django-enum-choices.git
pip install -e some-directory/django_enum_choices

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_choices-0.0.5.tar.gz (7.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_enum_choices-0.0.5-py2.py3-none-any.whl (14.5 kB view details)

Uploaded Python 2Python 3

File details

Details for the file django_enum_choices-0.0.5.tar.gz.

File metadata

  • Download URL: django_enum_choices-0.0.5.tar.gz
  • Upload date:
  • Size: 7.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.6.7

File hashes

Hashes for django_enum_choices-0.0.5.tar.gz
Algorithm Hash digest
SHA256 6c82083d3d7fb0fbd1d74261fe4c7ea12c7c6e0566de2b8e02ab6864bb08500a
MD5 d24356f48629383a8a74e55e32ca38a3
BLAKE2b-256 5d977181d24f9611095cda77980011f614481af5631907411887b7229df262a8

See more details on using hashes here.

File details

Details for the file django_enum_choices-0.0.5-py2.py3-none-any.whl.

File metadata

  • Download URL: django_enum_choices-0.0.5-py2.py3-none-any.whl
  • Upload date:
  • Size: 14.5 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.6.7

File hashes

Hashes for django_enum_choices-0.0.5-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 cf747a72881d3e617f225ddf5b080e0a26eece70cf3bceb8ec66d99cadff540f
MD5 dfa9d3e6040cc5472865a89447415aaa
BLAKE2b-256 fc9f67b24ccda726d4a09f056d5f512ab70e94c7d6396c897193cf64fbff0f41

See more details on using hashes here.

Supported by

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