项目作者: mbourqui

项目描述 :
Django model choices as Enum
高级语言: Python
项目地址: git://github.com/mbourqui/django-echoices.git
创建时间: 2017-04-21T13:01:14Z
项目社区:https://github.com/mbourqui/django-echoices

开源协议:MIT License

下载


Python
Django
License
PyPI
Build Status
Coverage Status

Django-EChoices

Choices for Django model fields as enumeration

Features

Requirements

Installation

Using PyPI

  1. Run pip install django-echoices.

Using the source code

  1. Make sure pandoc is installed
  2. Run ./pypi_packager.sh
  3. Run pip install dist/django_echoices-x.y.z-[...].wheel, where x.y.z must be replaced by the actual
    version number and [...] depends on your packaging configuration

Usage

Enumeration

First, define your choices enumeration (in your models.py for example):

  1. from echoices.enums import EChoice
  2. class EStates(EChoice):
  3. # format is: (value -> char or str or int, label -> str)
  4. CREATED = ('c', 'Created')
  5. SUBMITTED = ('s', 'Submitted')

Model field

Regular model field

Then, either use a regular model field:

  1. from django.db import models
  2. class MyModel(models.Model):
  3. state = models.CharField(max_length=EStates.max_value_length(),
  4. choices=EStates.choices(),
  5. default=EStates.CREATED.value)

Note: If your value is an int, you can use models.IntegerField instead.

Specialized field

You can also use specialized field. Using such a field, you will then only handle Echoice instances.

  1. from django.db import models
  2. from echoices.fields import make_echoicefield
  3. class MyModel(models.Model):
  4. # `max_length` is set automatically
  5. state = make_echoicefield(EStates, default=EStates.CREATED)

Note: MyModel.state will be Estates instance stored in a EStatesField field. See documentation
for more details.

WARNING: requires special handling of migrations. Read more in the documentation.

Derivation

You can add your own fields to the value and label ones. To do so, you have to override the init() and your
signature must look like: self, value, label, *args where you replace *args with your own positional arguments, as
you would do when defining a custom Enum. Do not call the super().init(), as value and label are already set
internally by EChoice.

As when dealing with a derived Enum, you can also add your own methods.

  1. from echoices.enums import EChoice
  2. class EMyChoices(EChoice):
  3. """Another variant of EChoice with additionnal content"""
  4. MY_CHOICE = (1, 'First choice', 'my additional value')
  5. def __init__(self, value, label, my_arg):
  6. self.my_arg = my_arg
  7. # Note: super().__init__() shall *not* be called!
  8. def show_myarg(self):
  9. """Used as: EMyChoices.MY_CHOICE.show_myarg()"""
  10. print(self.my_arg)
  11. @classmethod
  12. def show_all(cls):
  13. """Used as: EMyChoices.show_all()"""
  14. print(", ".join([e.my_arg for e in list(cls)]))

In templates

Assume a Context(dict(estates=myapp.models.EStates)) is provided to the following templates.

  • Fields of the EChoice can be accessed in the templates as:

    1. {{ estates.CREATED.value }}
    2. {{ estates.CREATED.label }}
  • EChoice can also be enumerated:

    1. {% for state in estates %}
    2. {{ state.value }}
    3. {{ state.label }}
    4. {% endfor %}

Short documentation

Specialized enum types" class="reference-link">Specialized enum types

enums.EChoice

Base enum type. Each enum element is a tuple (value, label), where [t]he first element
in each tuple is the actual value to be set on the model, and the second element is the human-readable name

doc. Values must be unique. Can be
derived for further customization.

enums.EOrderedChoice

Supports ordering of elements. EOrderedChoice.choices() takes an extra optional argument,
order, which supports three values: ‘sorted’, ‘reverse’ or ‘natural’ (default). If sorted, the choices are ordered
according to their value. If reverse, the choices are ordered according to their value as if each comparison were
reversed. If natural, the order is the one used when instantiating the enumeration.

enums.EAutoChoice

Generates auto-incremented numeric values. It’s then used like:

  1. from echoices.enums import EAutoChoice
  2. class EStates(EAutoChoice):
  3. # format is: label -> str
  4. CREATED = 'Created'
  5. SUBMITTED = 'Submitted'

API

Overriden EnumMeta methods
  • EChoice.__getitem__(), such that you can retrieve an EChoice instance using EChoice['my_value']
Additional classmethods
  • choices() generates the choices as expected by a Django model field
  • max_value_length() returns the max length for the Django model field, if the values are strings
  • values() returns a list of all the values
  • get(value, default=None) returns the EChoice instance having that value, else returns the default

Specialized model fields" class="reference-link">Specialized model fields

fields.EChoiceField via fields.make_echoicefield()

Deal directly with the enum instances instead of their DB storage value. The specialized field will be derived from a
models.Field subclass, the internal representation is deduced from the value type. So for example if the values are
strings, then the the EChoiceField will subclass models.CharField; and if the values are integers then it will be
models.IntegerField. Actually supports str, int, float and (non-null) bool as enum values.

make_echoicefield() will return an instance of EChoiceField which subclasses a field type from models.CharField.
The exact name of the field type will be MyEnumNameField in Django >= 1.9, note the suffixed ‘Field’. For earlier
versions of Django, it will be EChoiceField.

Thus, MyModel.my_echoice_field will be an EChoice instance stored in an EChoiceField field.

Migrations" class="reference-link">Migrations

Since the field is generated with the help of a factory function, it does not exist as is as a field class in
echoices.fields. But, when generating a migration file, Django will set the class of the field as the resulting class
from make_echoicefield(), which does not exist in echoices.fields. This will cause the Django server to crash, as
an AttributeError: module 'echoices.fields' has no attribute 'MyEnumNameField' exception will be raised.

To prevent this, you have to edit the migration file and replace the instantiation of the non-existing class with a call
to make_echoicefield(), with the same parameters as when defining the field in your model.

For example, assume you have the following model defined in models.py:

  1. from django.db import models
  2. from echoices.fields import make_echoicefield
  3. class MyModel(models.Model):
  4. state = make_echoicefield(EStates, default=EStates.CREATED)

Then you would replace the generated field instantiation statement in migrations/0001_initial.py

  1. migrations.CreateModel(
  2. name='MyModel',
  3. fields=[
  4. # Replace the statement below
  5. ('state', echoices.fields.EStatesField(
  6. echoices=app.models.EStates,
  7. default=app.models.EStates(1))
  8. ),
  9. ],

with

  1. ('state', echoices.fields.make_echoicefield(
  2. echoices=app.models.EStates,
  3. default=app.models.EStates.CREATED)
  4. ),

fields.MultipleEChoiceField

Similar to previous fields, but supports multiple values to be selected.
Not yet implemented.

Usage in templates" class="reference-link">Usage in templates

Assume a Context(dict(estates=myapp.models.EStates)) is provided to the following templates.

  • Fields of the EChoice can be accessed in the templates as:

    1. {{ estates.CREATED.value }}
    2. {{ estates.CREATED.label }}
  • EChoice can also be enumerated:

    1. {% for state in estates %}
    2. {{ state.value }}
    3. {{ state.label }}
    4. {% endfor %}