-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Add ENUM capability * Add additional testing * Clean up EnumField and update tests * Add type hinting to EnumField, remove patch from test as it's not needed * Add return type hinting
- Loading branch information
Showing
3 changed files
with
155 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
from enum import Enum | ||
from typing import Type, Optional, Union | ||
|
||
from rest_framework.fields import empty | ||
from rest_framework.serializers import ChoiceField | ||
|
||
|
||
class EnumField(ChoiceField): | ||
""" | ||
Custom DRF field that restricts accepted values to that of a defined enum | ||
""" | ||
|
||
default_error_messages = {"invalid": "No matching enum type"} | ||
|
||
def __init__(self, enum: Type[Enum], **kwargs): | ||
self.enum = enum | ||
kwargs.setdefault("choices", [(x, x.name) for x in self.enum]) | ||
super().__init__(**kwargs) | ||
|
||
def run_validation( | ||
self, data: Optional[Union[Enum, str, empty]] = empty | ||
) -> Optional[Enum]: | ||
if data and data != empty and not isinstance(data, self.enum): | ||
match_found = False | ||
for x in self.enum: | ||
if x.value == data: | ||
match_found = True | ||
break | ||
|
||
if not match_found: | ||
self.fail("invalid") | ||
|
||
return super().run_validation(data) | ||
|
||
def to_internal_value(self, data: Optional[Union[Enum, str]]) -> Enum: | ||
for choice in self.enum: | ||
if choice == data or choice.name == data or choice.value == data: | ||
return choice | ||
self.fail("invalid") | ||
|
||
def to_representation(self, value: Optional[Union[Enum, str]]) -> Optional[str]: | ||
if isinstance(value, self.enum): | ||
return value.value | ||
|
||
return value |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters