Fields¶
Note
EnumField
automatically determines the most appropriate database
column type based on the Enum
subclass it is assigned to.
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)[source]¶
Bases:
FlagField
,EnumPositiveBigIntegerField
A database field supporting flag enumerations with integer values that fit into 64 bytes or fewer
- 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)[source]¶
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)[source]¶
Bases:
EnumField
[Type
[str
]],CharField
A database field supporting enumerations with character values.
- __init__(enum: ~typing.Type[~enum.Enum] | None = None, primitive: ~typing.Type[str] | None = <class 'str'>, **kwargs)[source]¶
- 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)[source]¶
Bases:
EnumField
[Type
[date
]],DateField
A database field supporting enumerations with date values.
- get_db_prep_value(value, connection, prepared=False) Any [source]¶
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.
- 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)[source]¶
Bases:
EnumField
[Type
[datetime
]],DateTimeField
A database field supporting enumerations with datetime values.
- get_db_prep_value(value, connection, prepared=False) Any [source]¶
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.
- 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)[source]¶
Bases:
EnumField
[Type
[Decimal
]],DecimalField
A database field supporting enumerations with Decimal values.
- __init__(enum: Type[Enum] | None = None, primitive: Type[Decimal] | None = None, max_digits: int | None = None, decimal_places: int | None = None, **kwargs)[source]¶
- get_db_prep_save(value, connection)[source]¶
Override base class to avoid calling to_python() in Django < 4.
- get_db_prep_value(value, connection, prepared=False) Any [source]¶
Convert the field value into the Enum type and then pull its value out.
- get_prep_value(value: Any) Any [source]¶
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.
- 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)[source]¶
Bases:
EnumField
[Type
[timedelta
]],DurationField
A database field supporting enumerations with duration values.
- get_db_prep_value(value, connection, prepared=False) Any [source]¶
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.
- 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)[source]¶
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)[source]¶
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.
- from_db_value(value: Any, expression, connection) Any [source]¶
Convert the database field value into the Enum type.
- get_db_prep_value(value: Any, connection, prepared=False)[source]¶
Convert the field value into the Enum type and then pull its value out.
- get_prep_value(value: Any) Any [source]¶
Convert the database field value into the Enum type then convert that enum value into the smallest number of bytes that can hold it.
- 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)[source]¶
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
primitive – The primitive type of the enumeration if different than the default
strict – If True (default) the field will throw a
ValueError
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.
- __init__(enum: Type[Enum] | None = None, primitive: PrimitiveT | None = None, strict: bool = True, coerce: bool = True, constrained: bool | None = None, **kwargs)[source]¶
- 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 [source]¶
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
- deconstruct() Tuple[str, str, List, dict] [source]¶
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.
- descriptor_class¶
alias of
ToPythonDeferredAttribute
- property enum¶
The enumeration type
- formfield(form_class=None, choices_form_class=None, **kwargs)[source]¶
An override of
formfield()
that ensures we use the correct django-enum form field type:
- from_db_value(value: Any, expression, connection) Any [source]¶
Convert the database field value into the Enum type.
- get_db_prep_value(value, connection, prepared=False) Any [source]¶
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.
- property strict¶
True if the field requires values to be valid enumeration values
- to_python(value: Any) Enum | Any [source]¶
Converts the value in the enumeration type.
See
django.db.models.Field.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)[source]¶
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
django.db.models.Model.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[source]¶
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)[source]¶
Bases:
EnumField
[Type
[float
]],FloatField
A database field supporting enumerations with floating point values
- __init__(enum: Type[Enum] | None = None, primitive: Type[float] | None = None, strict: bool = True, coerce: bool = True, constrained: bool | None = None, **kwargs)[source]¶
- 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)[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
Bases:
EnumField
[Type
[time
]],TimeField
A database field supporting enumerations with time values.
- get_db_prep_value(value, connection, prepared=False) Any [source]¶
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.
- class django_enum.fields.EnumValidatorAdapter(*args, **kwargs)[source]¶
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.
- 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)[source]¶
Bases:
FlagField
,EnumExtraBigIntegerField
Flag fields that require more than 64 bits.
- contribute_to_class(cls, name, private_only: bool = False)[source]¶
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(enum: ~typing.Type[~enum.IntFlag] | None = None, blank=True, default=<class 'django.db.models.NOT_PROVIDED'>, **kwargs)[source]¶
Bases:
object
A common base class for EnumFields that store Flag enumerations and support bitwise operations.
- __init__(enum: ~typing.Type[~enum.IntFlag] | None = None, blank=True, default=<class 'django.db.models.NOT_PROVIDED'>, **kwargs)[source]¶
- contribute_to_class(cls: Type[Model], name: str, private_only: bool = False) None [source]¶
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
- formfield(form_class=None, choices_form_class=None, **kwargs)[source]¶
An override of
formfield()
that ensures we useEnumFlagField
.The default widget will be
FlagSelectMultiple
if the field is strict, andNonStrictFlagSelectMultiple
if not.
- 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)[source]¶
-
A mixin containing common implementation details for a database field supporting enumerations with integer values.
- __init__(enum: ~typing.Type[~enum.Enum] | None = None, primitive: ~typing.Type[int] | None = <class 'int'>, bit_length: int | None = None, **kwargs)[source]¶
- 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)[source]¶
Bases:
FlagField
,EnumPositiveIntegerField
A database field supporting flag enumerations with positive integer values that fit into 32 bytes or fewer
- 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)[source]¶
Bases:
FlagField
,EnumPositiveSmallIntegerField
A database field supporting flag enumerations with positive integer values that fit into 2 bytes or fewer
- class django_enum.fields.ToPythonDeferredAttribute(field)[source]¶
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.
- django_enum.fields.field¶
alias of
BigIntegerFlagField