Reference
Fields
Support for Django model fields built from enumeration types.
- class django_enum.fields.EnumBigIntegerField(*args, enum: Type[Enum] | None = None, strict: bool = True, coerce: bool = True, **kwargs)
Bases:
EnumMixin
,BigIntegerField
A database field supporting enumerations with integer values that fit into 64 bytes or fewer
- primitive
alias of
int
- class django_enum.fields.EnumCharField(*args, enum=None, **kwargs)
Bases:
EnumMixin
,CharField
A database field supporting enumerations with character values.
- primitive
alias of
str
- django_enum.fields.EnumField(enum: Type[Enum], *field_args, **field_kwargs) EnumMixin
This is a function, not a type. Some syntactic sugar that wraps the enum field metaclass so that we can cleanly create enums like so:
class MyModel(models.Model): class EnumType(IntegerChoices): VAL1 = 1, _('Value 1') VAL2 = 2, _('Value 2') VAL3 = 3, _('Value 3') field_name = EnumField(EnumType)
- Parameters:
enum – The class of the enumeration.
field_args – Any standard unnamed field arguments for the base field type.
field_kwargs – Any standard named field arguments for the base field type.
- Returns:
An object of the appropriate enum field type
- class django_enum.fields.EnumFloatField(*args, enum: Type[Enum] | None = None, strict: bool = True, coerce: bool = True, **kwargs)
Bases:
EnumMixin
,FloatField
A database field supporting enumerations with floating point values
- primitive
alias of
float
- class django_enum.fields.EnumIntegerField(*args, enum: Type[Enum] | None = None, strict: bool = True, coerce: bool = True, **kwargs)
Bases:
EnumMixin
,IntegerField
A database field supporting enumerations with integer values that fit into 32 bytes or fewer
- primitive
alias of
int
- class django_enum.fields.EnumMixin(*args, enum: Type[Enum] | None = None, strict: bool = True, coerce: bool = True, **kwargs)
Bases:
object
This mixin class turns any Django database field into an enumeration field. It works by overriding validation and pre/post database hooks to validate and convert any values to the Enumeration type in question.
- Parameters:
enum – The enum class
strict – If True (default) the field will throw ValueErrors if the value is not coercible to a valid enumeration type.
args – Any standard unnamed field arguments for the underlying field type.
field_kwargs – Any standard named field arguments for the underlying field type.
- _try_coerce(value: Any, force: bool = False) Enum | Any
Attempt coercion of value to enumeration type instance, if unsuccessful and non-strict, coercion to enum’s primitive type will be done, otherwise a ValueError is raised.
- coerce: bool = True
- deconstruct() Tuple[str, str, List, dict]
Preserve field migrations. Strict and coerce are omitted because reconstructed fields are always non-strict and coerce is always False.
Warning
Do not add enum to kwargs! It is important that migration files not reference enum classes that might be removed from the code base in the future as this would break older migration files! We simply use the choices tuple, which is plain old data and entirely sufficient to de/reconstruct our field.
See deconstruct
- descriptor_class
alias of
ToPythonDeferredAttribute
- enum: Type[Enum] | None = None
- formfield(form_class=None, choices_form_class=None, **kwargs)
- from_db_value(value: Any, expression, connection) Any
Convert the database field value into the Enum type.
See from_db_value
- get_db_prep_value(value, connection, prepared=False)
Convert the field value into the Enum type and then pull its value out.
- get_default() Any
Wrap get_default in an enum type coercion attempt
- get_prep_value(value: Any) Any
Convert the database field value into the Enum type.
See get_prep_value
- primitive: Type[Any]
- strict: bool = True
- to_python(value: Any) Enum | Any
Converts the value in the enumeration type.
See to_python
- Parameters:
value – The value to convert
- Returns:
The converted value
- Raises:
ValidationError – If the value is not mappable to a valid enumeration
- validate(value: Any, model_instance: Model)
Validates the field as part of model clean routines. Runs super class validation routines then tries to convert the value to a valid enumeration instance.
See full_clean
- Parameters:
value – The value to validate
model_instance – The model instance holding the value
- Raises:
ValidationError – if the value fails validation
- Returns:
- class django_enum.fields.EnumPositiveBigIntegerField(*args, enum: Type[Enum] | None = None, strict: bool = True, coerce: bool = True, **kwargs)
Bases:
EnumMixin
,PositiveBigIntegerField
A database field supporting enumerations with positive (but signed) integer values that fit into 64 bytes or fewer
- primitive
alias of
int
- class django_enum.fields.EnumPositiveIntegerField(*args, enum: Type[Enum] | None = None, strict: bool = True, coerce: bool = True, **kwargs)
Bases:
EnumMixin
,PositiveIntegerField
A database field supporting enumerations with positive (but signed) integer values that fit into 32 bytes or fewer
- primitive
alias of
int
- class django_enum.fields.EnumPositiveSmallIntegerField(*args, enum: Type[Enum] | None = None, strict: bool = True, coerce: bool = True, **kwargs)
Bases:
EnumMixin
,PositiveSmallIntegerField
A database field supporting enumerations with positive (but signed) integer values that fit into 2 bytes or fewer
- primitive
alias of
int
- class django_enum.fields.EnumSmallIntegerField(*args, enum: Type[Enum] | None = None, strict: bool = True, coerce: bool = True, **kwargs)
Bases:
EnumMixin
,SmallIntegerField
A database field supporting enumerations with integer values that fit into 2 bytes or fewer
- primitive
alias of
int
- class django_enum.fields.ToPythonDeferredAttribute(field)
Bases:
DeferredAttribute
Extend DeferredAttribute descriptor to run a field’s to_python method on a value anytime it is set on the model. This is used to ensure a EnumFields on models are always of their Enum type.
- class django_enum.fields._EnumFieldMetaClass(enum: Type[Enum])
Bases:
type
- SUPPORTED_PRIMITIVES = {<class 'int'>, <class 'float'>, <class 'str'>}
- django_enum.fields.with_typehint(baseclass: Type[T]) Type[T]
Change inheritance to add Field type hints when type checking is running. This is just more simple than defining a Protocol - revisit if Django provides Field protocol - should also just be a way to create a Protocol from a class?
This is icky but it works - revisit in future.
Choices
Support for symmetrical property enumeration types derived from Django choice types. These choices types are drop in replacements for the Django IntegerChoices and TextChoices.
- class django_enum.choices.DjangoEnumPropertiesMeta(classname, bases, classdict, **kwds)
Bases:
ChoicesType
Throw error if metaclass is used without enum-properties
Needs to be strict subclass of same metaclass as Enum to make it to the ImportError.
- django_enum.choices.DjangoSymmetricMixin
alias of
MissingEnumProperties
- class django_enum.choices.FloatChoices(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
MissingEnumProperties
,float
,Choices
Raises ImportError on class definition
- class django_enum.choices.IntegerChoices(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
MissingEnumProperties
,int
,Choices
Raises ImportError on class definition
- class django_enum.choices.MissingEnumProperties(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
Throw error if choice types are used without enum-properties
- class django_enum.choices.TextChoices(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
MissingEnumProperties
,str
,Choices
Raises ImportError on class definition
- django_enum.choices.choices(enum: Type[Enum] | None) List[Tuple[Any, str]]
Get the Django choices for an enumeration type. If the enum type has a choices attribute, it will be used. Otherwise, the choices will be derived from value, label pairs if the enumeration type has a label attribute, or the name attribute if it does not.
This is used for compat with enums that do not inherit from Django’s Choices type.
- Parameters:
enum – The enumeration type
- Returns:
A list of (value, label) pairs
- django_enum.choices.labels(enum: Type[Enum] | None) List[Any]
Return a list of labels to use for the enumeration type. See choices.
This is used for compat with enums that do not inherit from Django’s Choices type.
- Parameters:
enum – The enumeration type
- Returns:
A list of labels
- django_enum.choices.names(enum: Type[Enum] | None) List[Any]
Return a list of names to use for the enumeration type. This is used for compat with enums that do not inherit from Django’s Choices type.
- Parameters:
enum – The enumeration type
- Returns:
A list of labels
- django_enum.choices.values(enum: Type[Enum] | None) List[Any]
Return a list of the values of an enumeration type.
This is used for compat with enums that do not inherit from Django’s Choices type.
- Parameters:
enum – The enumeration type
- Returns:
A list of values
Filters
Support for django-filter
- django_enum.filters.EnumFilter
alias of
_MissingDjangoFilters
- django_enum.filters.FilterSet
alias of
_MissingDjangoFilters
- class django_enum.filters._MissingDjangoFilters(*args, **kwargs)
Bases:
object
Throw error if filter support is used without django-filter
Forms
Enumeration support for django model forms
- class django_enum.forms.EnumChoiceField(enum: ~typing.Type[~enum.Enum] | None = None, *, empty_value: ~typing.Any = <class 'django_enum.forms._Unspecified'>, strict: bool = True, empty_values: ~typing.List[~typing.Any] = [None, '', [], (), {}], choices: ~typing.Iterable[~typing.Tuple[~typing.Any, str]] = (), **kwargs)
Bases:
TypedChoiceField
The default
ChoiceField
will only accept the base enumeration values. Use this field on forms to accept any value mappable to an enumeration including any labels or symmetric properties.- Parameters:
enum – The Enumeration type
empty_value – Allow users to define what empty is because some enumeration types might use an empty value (i.e. empty string) as an enumeration value. This value will be returned when any “empty” value is encountered. If unspecified the default empty value of ‘’ is returned.
empty_values – Override the list of what are considered to be empty values.
strict – If False, values not included in the enumeration list, but of the same primitive type are acceptable.
choices – Override choices, otherwise enumeration choices attribute will be used.
kwargs – Any additional parameters to pass to ChoiceField base class.
- _coerce_to_value_type(value: Any) Any
Coerce the value to the enumerations value type
- coerce(value: Any) Enum | Any
Attempt conversion of value to an enumeration value and return it if successful.
Note
When used to represent a model field, by default the model field’s to_python method will be substituted for this method.
- Parameters:
value – The value to convert
- Raises:
ValidationError – if a valid return value cannot be determined.
- Returns:
An enumeration value or the canonical empty value if value is one of our empty_values, or the value itself if this is a non-strict field and the value is of a matching primitive type
- empty_value: Any = ''
- empty_values: List[Any] = [None, '', [], (), {}]
- property enum
the class of the enumeration
- enum_: Type[Enum] | None = None
- prepare_value(value: Any) Any
Must return the raw enumeration value type
- property strict
strict fields allow non-enumeration values
- strict_: bool = True
- to_python(value: Any) Enum | Any
Return the value as its full enumeration object
- valid_value(value: Any) bool
Return false if this value is not valid
- validate(value)
Validate that the input is in self.choices.
- class django_enum.forms.NonStrictSelect(attrs=None, choices=())
Bases:
Select
A Select widget for non-strict EnumChoiceFields that includes any existing non-conforming value as a choice option.
- property media
- render(*args, **kwargs)
Before rendering if we’re a non-strict field and our value is not one of our choices, we add it as an option.
Serializer Fields
Support for django rest framework symmetric serialization
- django_enum.drf.EnumField
alias of
_MissingDjangoRestFramework