Reference¶
Fields¶
Support for Django model fields built from enumeration types.
- class django_enum.fields.BigIntegerFlagField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
FlagField
,EnumPositiveBigIntegerField
A database field supporting flag enumerations with integer values that fit into 64 bytes or fewer
- class_lookups = {'has_all': <class 'django_enum.query.HasAllFlagsLookup'>, 'has_any': <class 'django_enum.query.HasAnyFlagsLookup'>}¶
- django_enum.fields.DatabaseDefault¶
alias of
_DatabaseDefault
- class django_enum.fields.EnumBigIntegerField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
IntEnumField
,BigIntegerField
A database field supporting enumerations with integer values that fit into 64 bytes or fewer
- class django_enum.fields.EnumCharField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
EnumField
[Type
[str
]],CharField
A database field supporting enumerations with character values.
- empty_values = [None, [], (), {}]¶
- property primitive¶
The most appropriate primitive non-Enumeration type that can represent all enumeration values. Deriving classes should return their canonical primitive type if this type is None. The reason for this is that the primitive type of an enumeration might be a derived class of the canonical primitive type (e.g. str or int), but this primitive type will not always be available - for instance in migration code. Migration code should only ever deal with the most basic python types to reduce the dependency footprint on externally defined code - in all but the weirdest cases this will work.
- class django_enum.fields.EnumDateField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
EnumField
[Type
[date
]],DateField
A database field supporting enumerations with date values.
- get_db_prep_value(value, connection, prepared=False) Any ¶
Convert the field value into the Enum type and then pull its value out.
- property primitive¶
The most appropriate primitive non-Enumeration type that can represent all enumeration values. Deriving classes should return their canonical primitive type if this type is None. The reason for this is that the primitive type of an enumeration might be a derived class of the canonical primitive type (e.g. str or int), but this primitive type will not always be available - for instance in migration code. Migration code should only ever deal with the most basic python types to reduce the dependency footprint on externally defined code - in all but the weirdest cases this will work.
- 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
- value_to_string(obj)¶
Return a string value of this field from the passed obj. This is used by the serialization framework.
- class django_enum.fields.EnumDateTimeField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
EnumField
[Type
[datetime
]],DateTimeField
A database field supporting enumerations with datetime values.
- get_db_prep_value(value, connection, prepared=False) Any ¶
Convert the field value into the Enum type and then pull its value out.
- property primitive¶
The most appropriate primitive non-Enumeration type that can represent all enumeration values. Deriving classes should return their canonical primitive type if this type is None. The reason for this is that the primitive type of an enumeration might be a derived class of the canonical primitive type (e.g. str or int), but this primitive type will not always be available - for instance in migration code. Migration code should only ever deal with the most basic python types to reduce the dependency footprint on externally defined code - in all but the weirdest cases this will work.
- 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
- value_to_string(obj)¶
Return a string value of this field from the passed obj. This is used by the serialization framework.
- class django_enum.fields.EnumDecimalField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
EnumField
[Type
[Decimal
]],DecimalField
A database field supporting enumerations with Decimal values.
- get_db_prep_save(value, connection)¶
Override base class to avoid calling to_python() in Django < 4.
- get_db_prep_value(value, connection, prepared=False) Any ¶
Convert the field value into the Enum type and then pull its value out.
- get_prep_value(value: Any) Any ¶
By-pass base class - it calls to_python() which we don’t want.
- property primitive¶
The most appropriate primitive non-Enumeration type that can represent all enumeration values. Deriving classes should return their canonical primitive type if this type is None. The reason for this is that the primitive type of an enumeration might be a derived class of the canonical primitive type (e.g. str or int), but this primitive type will not always be available - for instance in migration code. Migration code should only ever deal with the most basic python types to reduce the dependency footprint on externally defined code - in all but the weirdest cases this will work.
- 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
- validators¶
- value_to_string(obj)¶
Return a string value of this field from the passed obj. This is used by the serialization framework.
- class django_enum.fields.EnumDurationField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
EnumField
[Type
[timedelta
]],DurationField
A database field supporting enumerations with duration values.
- get_db_prep_value(value, connection, prepared=False) Any ¶
Convert the field value into the Enum type and then pull its value out.
- property primitive¶
The most appropriate primitive non-Enumeration type that can represent all enumeration values. Deriving classes should return their canonical primitive type if this type is None. The reason for this is that the primitive type of an enumeration might be a derived class of the canonical primitive type (e.g. str or int), but this primitive type will not always be available - for instance in migration code. Migration code should only ever deal with the most basic python types to reduce the dependency footprint on externally defined code - in all but the weirdest cases this will work.
- 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
- value_to_string(obj)¶
Return a string value of this field from the passed obj. This is used by the serialization framework.
- class django_enum.fields.EnumExtraBigIntegerField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
IntEnumField
,BinaryField
A database field supporting enumerations with integer values that require more than 64 bits. This field only works for Enums that inherit from int. This field stores enum values in big endian byte order.
- contribute_to_class(cls, name, private_only: bool = False)¶
Register the field with the model class it belongs to.
If private_only is True, create a separate instance of this field for every subclass of cls, even if cls is not an abstract model.
- description¶
- 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: Any, connection, prepared=False)¶
Convert the field value into the Enum type and then pull its value out.
- get_prep_value(value: Any) Any ¶
Convert the database field value into the Enum type then convert that enum value into the smallest number of bytes that can hold it.
See get_prep_value
- signed¶
True if the enum has negative values
- class django_enum.fields.EnumField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
Generic
[PrimitiveT
],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.
coerce – If True (default) the field will always coerce values to the enum type when possible. If False, the field will contain the primitive type of the enumeration.
constrained – If True (default) and strict is also true CheckConstraints will be added to the model to constrain values of the database column to values of the enumeration type. If True and strict is False constraints will still be added.
args – Any standard unnamed field arguments for the underlying field type.
field_kwargs – Any standard named field arguments for the underlying field type.
- _coerce_: bool = True¶
- _coerce_to_value_type(value: Any) Any ¶
Coerce the value to the enumerations value type
- _constrained_: bool = True¶
- _enum_: Type[Enum] | None = None¶
- _fallback(value: Any) Any ¶
Allow deriving classes to implement a final fallback coercion attempt.
- _primitive_: PrimitiveT | None = None¶
- _strict_: bool = True¶
- _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.
- _value_primitives_: List[Any] = []¶
- property coerce¶
False if the field should not coerce values to the enumeration type
- property constrained¶
False if the database values are not constrained to the enumeration. By default this is set to the value of strict.
- static constraint_name(model_class: Type[Model], field_name: str, enum: Type[Enum]) str ¶
Get a check constraint name for the given enumeration field on the given model class. Check constraint names are limited to MAX_CONSTRAINT_NAME_LENGTH. The beginning parts of the name will be chopped off if it is too long.
- Parameters:
model_class – The class of the Model the field is on
field_name – The name of the field
enum – The enumeration type of the EnumField
- contribute_to_class(cls: Type[Model], name: str, private_only: bool = False)¶
- 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
- default_error_messages: Any¶
- descriptor_class¶
alias of
ToPythonDeferredAttribute
- property enum¶
The enumeration type
- 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_choices(include_blank=True, blank_choice=(('', '---------'),), limit_choices_to=None, ordering=())¶
- get_db_prep_value(value, connection, prepared=False) Any ¶
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
- property primitive¶
The most appropriate primitive non-Enumeration type that can represent all enumeration values. Deriving classes should return their canonical primitive type if this type is None. The reason for this is that the primitive type of an enumeration might be a derived class of the canonical primitive type (e.g. str or int), but this primitive type will not always be available - for instance in migration code. Migration code should only ever deal with the most basic python types to reduce the dependency footprint on externally defined code - in all but the weirdest cases this will work.
- property strict¶
True if the field requires values to be valid enumeration values
- 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 | None)¶
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.EnumFieldFactory¶
Bases:
type
Metaclass for EnumField that allows us to dynamically create a EnumFields based on their python Enum class types.
- class django_enum.fields.EnumFloatField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
EnumField
[Type
[float
]],FloatField
A database field supporting enumerations with floating point values
- _fallback(value: Any) Any ¶
Allow deriving classes to implement a final fallback coercion attempt.
- _tolerance_: float¶
- property primitive¶
The most appropriate primitive non-Enumeration type that can represent all enumeration values. Deriving classes should return their canonical primitive type if this type is None. The reason for this is that the primitive type of an enumeration might be a derived class of the canonical primitive type (e.g. str or int), but this primitive type will not always be available - for instance in migration code. Migration code should only ever deal with the most basic python types to reduce the dependency footprint on externally defined code - in all but the weirdest cases this will work.
- class django_enum.fields.EnumIntegerField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
IntEnumField
,IntegerField
A database field supporting enumerations with integer values that fit into 32 bytes or fewer
- class django_enum.fields.EnumPositiveBigIntegerField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
IntEnumField
,PositiveBigIntegerField
A database field supporting enumerations with positive (but signed) integer values that fit into 64 bytes or fewer
- class django_enum.fields.EnumPositiveIntegerField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
IntEnumField
,PositiveIntegerField
A database field supporting enumerations with positive (but signed) integer values that fit into 32 bytes or fewer
- class django_enum.fields.EnumPositiveSmallIntegerField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
IntEnumField
,PositiveSmallIntegerField
A database field supporting enumerations with positive (but signed) integer values that fit into 2 bytes or fewer
- class django_enum.fields.EnumSmallIntegerField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
IntEnumField
,SmallIntegerField
A database field supporting enumerations with integer values that fit into 2 bytes or fewer
- class django_enum.fields.EnumTimeField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
EnumField
[Type
[time
]],TimeField
A database field supporting enumerations with time values.
- get_db_prep_value(value, connection, prepared=False) Any ¶
Convert the field value into the Enum type and then pull its value out.
- property primitive¶
The most appropriate primitive non-Enumeration type that can represent all enumeration values. Deriving classes should return their canonical primitive type if this type is None. The reason for this is that the primitive type of an enumeration might be a derived class of the canonical primitive type (e.g. str or int), but this primitive type will not always be available - for instance in migration code. Migration code should only ever deal with the most basic python types to reduce the dependency footprint on externally defined code - in all but the weirdest cases this will work.
- 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
- value_to_string(obj)¶
Return a string value of this field from the passed obj. This is used by the serialization framework.
- class django_enum.fields.EnumValidatorAdapter(*args, **kwargs)¶
Bases:
object
A wrapper for validators that expect a primitive type that enables them to receive an Enumeration value instead. Some automatically added field validators must be wrapped.
- deconstruct()¶
Return a 3-tuple of class import path, positional arguments, and keyword arguments.
- wrapped: Type¶
- class django_enum.fields.ExtraBigIntegerFlagField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
FlagField
,EnumExtraBigIntegerField
Flag fields that require more than 64 bits.
- contribute_to_class(cls, name, private_only: bool = False)¶
Add check constraints that honor flag fields range and boundary setting. Bypass EnumField’s contribute_to_class() method, which adds constraints that are too specific.
- Boundary settings:
“strict” -> error is raised [default for Flag] “conform” -> extra bits are discarded “eject” -> lose flag status [default for IntFlag] “keep” -> keep flag status and all bits
The constraints here are designed to make sense given the boundary setting, ensure that simple database reads through the ORM cannot throw exceptions and that search behaves as expected.
KEEP: no constraints
EJECT: constrained to the enum’s range if strict is True
- CONFORM: constrained to the enum’s range. It would be possible to
insert and load an out of range value, but that value would not be searchable so a constraint is added.
STRICT: constrained to the enum’s range
- class django_enum.fields.FlagField¶
Bases:
object
A common base class for EnumFields that store Flag enumerations and support bitwise operations.
- contribute_to_class(cls: Type[Model], name: str, private_only: bool = False) None ¶
Add check constraints that honor flag fields range and boundary setting. Bypass EnumField’s contribute_to_class() method, which adds constraints that are too specific.
- Boundary settings:
“strict” -> error is raised [default for Flag] “conform” -> extra bits are discarded “eject” -> lose flag status [default for IntFlag] “keep” -> keep flag status and all bits
The constraints here are designed to make sense given the boundary setting, ensure that simple database reads through the ORM cannot throw exceptions and that search behaves as expected.
KEEP: no constraints
EJECT: constrained to the enum’s range if strict is True
- CONFORM: constrained to the enum’s range. It would be possible to
insert and load an out of range value, but that value would not be searchable so a constraint is added.
STRICT: constrained to the enum’s range
- enum: Type[Flag]¶
- class django_enum.fields.IntEnumField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
EnumField
[Type
[int
]]A mixin containing common implementation details for a database field supporting enumerations with integer values.
- property bit_length¶
The minimum number of bits required to represent all primitive values of the enumeration
- property primitive¶
The common primitive type of the enumeration values. This will always be int or a subclass of int.
- class django_enum.fields.IntegerFlagField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
FlagField
,EnumPositiveIntegerField
A database field supporting flag enumerations with positive integer values that fit into 32 bytes or fewer
- class_lookups = {'has_all': <class 'django_enum.query.HasAllFlagsLookup'>, 'has_any': <class 'django_enum.query.HasAnyFlagsLookup'>}¶
- class django_enum.fields.SmallIntegerFlagField(enum: Type[Enum] | None = None, primitive: Type[int | str | float | date | datetime | time | timedelta | Decimal] | None = None, bit_length: int | None = None, **field_kwargs)¶
Bases:
FlagField
,EnumPositiveSmallIntegerField
A database field supporting flag enumerations with positive integer values that fit into 2 bytes or fewer
- class_lookups = {'has_all': <class 'django_enum.query.HasAllFlagsLookup'>, 'has_any': <class 'django_enum.query.HasAnyFlagsLookup'>}¶
- 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._DatabaseDefault¶
Bases:
object
Spoof DatabaseDefault for Django < 5.0
- django_enum.fields.field¶
alias of
BigIntegerFlagField
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, **kwargs)¶
Bases:
EnumPropertiesMeta
,ChoicesMeta
A composite meta class that combines Django’s Choices metaclass with enum-properties metaclass. This metaclass will add Django’s expected choices attribute and label properties to enumerations and enum-properties’ generic property support.
- property choices¶
For some eccentric enums list(Enum) is empty, so we override choices if empty
- property names¶
For some eccentric enums list(Enum) is empty, so we override names if empty
- class django_enum.choices.DjangoSymmetricMixin¶
Bases:
SymmetricMixin
An enumeration mixin that makes Django’s Choices type label field symmetric.
- _symmetric_builtins_ = ['name', 'label']¶
- class django_enum.choices.FlagChoices(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Bases:
DecomposeMixin
,DjangoSymmetricMixin
,IntFlag
,Choices
An integer flag enumeration type that accepts enum-properties property lists.
- _all_bits_ = 0¶
- _boundary_ = 'keep'¶
- _ep_coerce_types_ = []¶
- _ep_isymmetric_map_ = {}¶
- _ep_symmetric_map_ = {}¶
- _flag_mask_ = 0¶
- static _generate_next_value_(name, start, count, last_values)¶
Generate the next value when not given.
name: the name of the member start: the initial start value or None count: the number of existing members last_values: the list of values assigned
- _inverted_ = None¶
- _properties_ = ['label']¶
- _singles_mask_ = 0¶
- label: str¶
- class django_enum.choices.FloatChoices(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Bases:
DjangoSymmetricMixin
,float
,Choices
A floating point enumeration type that accepts enum-properties property lists.
- _ep_coerce_types_ = []¶
- _ep_isymmetric_map_ = {}¶
- _ep_symmetric_map_ = {}¶
- _properties_ = ['label']¶
- label: str¶
- class django_enum.choices.IntegerChoices(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Bases:
DjangoSymmetricMixin
,IntegerChoices
An integer enumeration type that extends Django’s IntegerChoices and accepts enum-properties property lists.
- _ep_coerce_types_ = []¶
- _ep_isymmetric_map_ = {}¶
- _ep_symmetric_map_ = {}¶
- _properties_ = ['label']¶
- label: str¶
- class django_enum.choices.TextChoices(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Bases:
DjangoSymmetricMixin
,TextChoices
A character enumeration type that extends Django’s TextChoices and accepts enum-properties property lists.
- _ep_coerce_types_ = []¶
- _ep_isymmetric_map_ = {}¶
- _ep_symmetric_map_ = {}¶
- static _generate_next_value_(name, start, count, last_values)¶
Generate the next value when not given.
name: the name of the member start: the initial start value or None count: the number of existing members last_values: the list of values assigned
- _properties_ = ['label']¶
- label: str¶
Filters¶
Support for django-filter
- class django_enum.filters.EnumFilter(*, enum, strict=False, **kwargs)¶
Bases:
TypedChoiceFilter
Use this filter class instead of
ChoiceFilter
to get filters to accept Enum labels and symmetric properties.For example if we have an enumeration field defined with the following Enum:
class Color(TextChoices, s('rgb'), s('hex', case_fold=True)): RED = 'R', 'Red', (1, 0, 0), 'ff0000' GREEN = 'G', 'Green', (0, 1, 0), '00ff00' BLUE = 'B', 'Blue', (0, 0, 1), '0000ff' color = EnumField(Color)
The default
ChoiceFilter
will only work with the enumeration values: ?color=R, ?color=G, ?color=B.EnumFilter
will accept query parameter values from any of the symmetric properties: ?color=Red, ?color=ff0000, etc…- Parameters:
enum – The class of the enumeration containing the values to filter on
strict – If False (default), values not in the enumeration will be searchable.
kwargs – Any additional arguments for base classes
- field_class¶
alias of
EnumChoiceField
- class django_enum.filters.FilterSet(data=None, queryset=None, *, request=None, prefix=None)¶
Bases:
FilterSet
Use this class instead of django-filter’s
FilterSet
class to automatically set allEnumField
filters toEnumFilter
by default instead ofChoiceFilter
.- _meta = <django_filters.filterset.FilterSetOptions object>¶
- base_filters = {}¶
- declared_filters = {}¶
- classmethod filter_for_lookup(field: Field, lookup_type: str) Tuple[Type[Filter], dict] ¶
For EnumFields use the EnumFilter class by default
Forms¶
Enumeration support for django model forms
- class django_enum.forms.EnumChoiceField(enum: ~typing.Type[~enum.Enum] | None = None, primitive: ~typing.Type | None = None, *, empty_value: ~typing.Any = <class 'django_enum.forms._Unspecified'>, strict: bool = True, empty_values: ~typing.List[~typing.Any] | ~typing.Type[~django_enum.forms._Unspecified] = <class 'django_enum.forms._Unspecified'>, choices: ~typing.Iterable[~typing.Tuple[~typing.Any, ~typing.Any] | ~typing.Tuple[str, ~typing.Iterable[~typing.Tuple[~typing.Any, ~typing.Any]]]] | ~django_enum.forms._ChoicesCallable = (), coerce: ~django_enum.forms._CoerceCallable | None = None, **kwargs)¶
Bases:
ChoiceFieldMixin
,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.
- class django_enum.forms.EnumFlagField(enum: ~typing.Type[~django.db.models.enums.Choices] | None = None, *, empty_value: ~typing.Any = <class 'django_enum.forms._Unspecified'>, strict: bool = True, empty_values: ~typing.List[~typing.Any] | ~typing.Type[~django_enum.forms._Unspecified] = <class 'django_enum.forms._Unspecified'>, choices: ~typing.Iterable[~typing.Tuple[~typing.Any, ~typing.Any] | ~typing.Tuple[str, ~typing.Iterable[~typing.Tuple[~typing.Any, ~typing.Any]]]] | ~django_enum.forms._ChoicesCallable = (), **kwargs)¶
Bases:
ChoiceFieldMixin
,TypedMultipleChoiceField
The default
TypedMultipleChoiceField
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.Behavior:
- if no select value in post data:
if null=True, no choice is null. If null=False, no choice is Enum(0)
- if select value in post data:
if null=True or False, no choice is Enum(0)
if strict=False, values can be outside of the enumerations
- class django_enum.forms.FlagSelectMultiple(attrs=None, choices=())¶
Bases:
SelectMultiple
A SelectMultiple widget for EnumFlagFields.
- property media¶
Query¶
Specialized has_any and has_all query lookups for flag enumerations.
- class django_enum.query.HasAllFlagsLookup(*args, **kwargs)¶
Bases:
Exact
Extend Exact lookup to support lookup on has all flags. This lookup bitwise ANDs the column with the lookup value and checks that the result is equal to the lookup value.
- get_rhs_op(connection, rhs)¶
- lookup_name = 'has_all'¶
- process_lhs(compiler, connection, lhs=None)¶
- class django_enum.query.HasAnyFlagsLookup(*args, **kwargs)¶
Bases:
HasAllFlagsLookup
Extend Exact lookup to support lookup on has any flags. This bitwise ANDs the column with the lookup value and checks that the result is greater than zero.
- get_rhs_op(connection, rhs)¶
- lookup_name = 'has_any'¶
- process_rhs(compiler, connection)¶
Serializer Fields¶
Support for django rest framework symmetric serialization
- class django_enum.drf.EnumField(*args, **kwargs)¶
Bases:
ChoiceField
A djangorestframework serializer field for Enumeration types. If unspecified ModelSerializers will assign django_enum.fields.EnumField model field types to ChoiceFields. ChoiceFields do not accept symmetrical values, this field will.
- Parameters:
enum – The type of the Enumeration of the field
strict – If True (default) only values in the Enumeration type will be acceptable. If False, no errors will be thrown if other values of the same primitive type are used
kwargs – Any other named arguments applicable to a ChoiceField will be passed up to the base classes.
- enum: Type[Enum]¶
- primitive: Type[Any]¶
- primitive_field: Type[Field] | None = None¶
- strict: bool = True¶
- to_internal_value(data: Any) Enum | Any ¶
Transform the incoming primitive data into an enum instance.
- to_representation(value: Any) Any ¶
Transform the outgoing enum value into its primitive value.
- class django_enum.drf.EnumFieldMixin¶
Bases:
object
A mixin for ModelSerializers that adds auto-magic support for EnumFields.
- build_standard_field(field_name, model_field)¶
The default implementation of build_standard_field will set any field with choices to a ChoiceField. This will override that for EnumFields and add enum and strict arguments to the field’s kwargs.
To use this mixin, include it before ModelSerializer in your serializer’s class hierarchy:
..code-block:: python
from django_enum.drf import EnumFieldMixin from rest_framework.serializers import ModelSerializer
class MySerializer(EnumFieldMixin, ModelSerializer):
- class Meta:
model = MyModel fields = ‘__all__’
- Parameters:
field_name – The name of the field on the serializer
model_field – The Field instance on the model
- Returns:
A 2-tuple, the first element is the field class, the second is the kwargs for the field
URLs¶
A metaclass and converter for Django’s URL dispatcher to use with Python’s Enum class.
- django_enum.urls.register_enum_converter(enum: Type[Enum], type_name='', prop='value')¶
Register an enum converter for Django’s URL dispatcher.
- Parameters:
enum – The enumeration type to register.
type_name – the name to use for the converter
prop – The property name to use to generate urls - by default the value is used.
utilities¶
Utility routines for django_enum.
- django_enum.utils.choices(enum_cls: Type[Enum] | None, override: bool = False) 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_cls – The enumeration type
override – Do not defer to choices attribute on the class if True
- Returns:
A list of (value, label) pairs
- django_enum.utils.decimal_params(enum: Type[Enum] | None, decimal_places: int | None = None, max_digits: int | None = None) Dict[str, int] ¶
Determine the maximum number of digits and decimal places required to represent all values of the enumeration class.
- Parameters:
enum – The enumeration class to determine the decimal parameters for
decimal_places – Use this value for decimal_places rather than the computed value
max_digits – Use this value for max_digits rather than the computed value
- Returns:
A tuple of (max_digits, decimal_places)
- django_enum.utils.determine_primitive(enum: Type[Enum]) Type | None ¶
Determine the python type most appropriate to represent all values of the enumeration class. The primitive type determination algorithm is thus:
Determine the types of all the values in the enumeration
Determine the first supported primitive type in the enumeration class inheritance tree
If there is only one value type, use its type as the primitive
If there are multiple value types and they are all subclasses of the class primitive type, use the class primitive type. If there is no class primitive type use the first supported primitive type that all values are symmetrically coercible to. If there is no such type, return None
By definition all values of the enumeration with the exception of None may be coerced to the primitive type and vice-versa.
- Parameters:
enum – The enumeration class to determine the primitive type for
- Returns:
A python type or None if no primitive type could be determined
- django_enum.utils.get_set_bits(flag: int | IntFlag) List[int] ¶
Return the indices of the bits set in the flag.
- Parameters:
flag – The flag to get the set bits for, value must be an int.
- Returns:
A list of indices of the set bits
- django_enum.utils.labels(enum_cls: 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_cls – The enumeration type
- Returns:
A list of labels
- django_enum.utils.names(enum_cls: Type[Enum] | None, override: bool = False) 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_cls – The enumeration type
override – Do not defer to names attribute on the class if True
- Returns:
A list of labels
- django_enum.utils.values(enum_cls: 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_cls – The enumeration type
- Returns:
A list of values
- django_enum.utils.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.