DRF¶
Support for django rest framework symmetric serialization
- class django_enum.drf.EnumField(*args, **kwargs)[source]¶
Bases:
ChoiceFieldA djangorestframework serializer field for Enumeration types. If unspecified ModelSerializers will assign
EnumFieldmodel field types to ChoiceField which will 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.
- class django_enum.drf.EnumFieldMixin[source]¶
Bases:
objectA mixin for ModelSerializers that adds auto-magic support for EnumFields.
- build_standard_field(field_name: str, model_field: EnumField) tuple[type[Field], dict[str, Any]][source]¶
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:
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
- class django_enum.drf.FlagField(*args, **kwargs)[source]¶
Bases:
MultipleChoiceFieldA djangorestframework serializer field for
Flagtypes. If unspecified ModelSerializers will assignFlagFieldmodel field types to ChoiceField which will not combine composite flag values appropriately. This field will also allow any symmetric values to be used (e.g. labels or names instead of values).You should add
EnumFieldMixinto your serializer to automatically use this field.- Parameters:
enum – The type of the flag of the field
strict – If True (default) only values in the flag 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.
- to_internal_value(data: Any) Enum | Any[source]¶
Transform the incoming primitive data into an enum instance. We accept a composite flag value or a list of values. If a list, each element will be converted to a flag value and then the values will be reduced into a composite value with the or operator.
- Returns:
A composite flag value.