|
| 1 | +"""Support for django rest framework symmetric serialization""" |
| 2 | + |
| 3 | + |
| 4 | +try: |
| 5 | + from typing import Any, Type, Union |
| 6 | + |
| 7 | + from django.db.models import Choices |
| 8 | + from rest_framework.fields import ChoiceField |
| 9 | + |
| 10 | + class EnumField(ChoiceField): |
| 11 | + """ |
| 12 | + A djangorestframework serializer field for Enumeration types. If |
| 13 | + unspecified ModelSerializers will assign django_enum.fields.EnumField |
| 14 | + model field types to ChoiceFields. ChoiceFields do not accept |
| 15 | + symmetrical values, this field will. |
| 16 | +
|
| 17 | + :param enum: The type of the Enumeration of the field |
| 18 | + :param strict: If True (default) only values in the Enumeration type |
| 19 | + will be acceptable. If False, no errors will be thrown if other |
| 20 | + values of the same primitive type are used |
| 21 | + :param kwargs: Any other named arguments applicable to a ChoiceField |
| 22 | + will be passed up to the base classes. |
| 23 | + """ |
| 24 | + |
| 25 | + enum: Type[Choices] |
| 26 | + strict: bool = True |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + enum: Type[Choices], |
| 31 | + strict: bool = strict, |
| 32 | + **kwargs |
| 33 | + ): |
| 34 | + self.enum = enum |
| 35 | + self.strict = strict |
| 36 | + self.choices = kwargs.pop('choices', enum.choices) |
| 37 | + super().__init__(choices=self.choices, **kwargs) |
| 38 | + |
| 39 | + def to_internal_value(self, data: Any) -> Union[Choices, Any]: |
| 40 | + """ |
| 41 | + Transform the *incoming* primitive data into an enum instance. |
| 42 | + """ |
| 43 | + if data == '' and self.allow_blank: |
| 44 | + return '' |
| 45 | + |
| 46 | + if not isinstance(data, self.enum): |
| 47 | + try: |
| 48 | + data = self.enum(data) |
| 49 | + except (TypeError, ValueError): |
| 50 | + try: |
| 51 | + data = type(self.enum.values[0])(data) |
| 52 | + data = self.enum(data) |
| 53 | + except (TypeError, ValueError): |
| 54 | + if self.strict or not isinstance( |
| 55 | + data, |
| 56 | + type(self.enum.values[0]) |
| 57 | + ): |
| 58 | + self.fail('invalid_choice', input=data) |
| 59 | + return data |
| 60 | + |
| 61 | + def to_representation(self, value: Any) -> Any: |
| 62 | + """ |
| 63 | + Transform the *outgoing* enum value into its primitive value. |
| 64 | + """ |
| 65 | + return getattr(value, 'value', value) |
| 66 | + |
| 67 | + |
| 68 | +except (ImportError, ModuleNotFoundError): |
| 69 | + |
| 70 | + class _MissingDjangoRestFramework: |
| 71 | + """Throw error if drf support is used without djangorestframework""" |
| 72 | + |
| 73 | + def __init__(self, *args, **kwargs): |
| 74 | + raise ImportError( |
| 75 | + f'{self.__class__.__name__} requires djangorestframework to ' |
| 76 | + f'be installed.' |
| 77 | + ) |
| 78 | + |
| 79 | + EnumField = _MissingDjangoRestFramework # type: ignore |
0 commit comments