What is the best way to write a serializer for enum and subsequent display in drf_spectacular?
I want to create a constructor for enum serializers to use them in views later and correctly display data in Swagger, especially in the schema.
My typical enum:
class EServicePlatform(models.IntegerChoices):
ONLINE = 1, 'Online'
OFFLINE = 2, 'Offline'
Which are directly sent to views as a dictionary:
django Copy code
class DictionaryPlatforms(APIView):
@extend_schema(responses={
200: OpenApiResponse(response=DictionarySerializer(enum_class=EServicePlatform, many=True)),
400: OpenApiResponse(description='Bad Request')}
)
def get(self, request, *args, **kwargs):
data = [{"value": item.value, "label": item.label} for item in EServicePlatform]
serializer = DictionarySerializer(data=data, many=True, enum_class=EServicePlatform)
if serializer.is_valid():
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
The serializer constructor itself:
class DictionarySerializer(serializers.Serializer):
value = serializers.ChoiceField(choices=[]) # Set an empty list by default
label = serializers.CharField()
def __init__(self, *args, **kwargs):
# Expect enum_class to be passed via kwargs
enum_class = kwargs.pop('enum_class', None)
if not enum_class:
raise ValueError("enum_class is required")
# Dynamically set choices based on the passed enum class
self.fields['value'].choices = enum_class.choices
super().__init__(*args, **kwargs)
self.enum_class = enum_class
def validate(self, data):
# Automatically add the label corresponding to the value
data['label'] = dict(self.enum_class.choices)[data['value']]
return data
In the current implementation, two problems arise:
- It seems to me that the logic is overly complicated and it can be significantly simplified. But how?
- For some reason, Swagger pulls data from a different enum, which is in another application entirely, and not from the one we are passing.