oxan/djangorestframework-dataclasses

EnumField does not seem to be compatible with other libraries that introspect ChoiceField

samrensenhouse opened this issue · 1 comments

I am currently using https://github.com/axnsan12/drf-yasg which does a lot of introspection on serializers. Using a dataclass with an enum causes it to fail due to it expecting to be able to pass a string to the ChoiceField to_representation method, but this library expects the passed value to only be an enum.

Snippet to show how drf_yasg is trying to call the to_representation method:

if isinstance(field, serializers.ChoiceField):
    enum_type = openapi.TYPE_STRING
    enum_values = []
    for choice in field.choices.keys():
        if isinstance(field, serializers.MultipleChoiceField):
            choice = field_value_to_representation(field, [choice])[0]
        else:
            choice = field_value_to_representation(field, choice)

        enum_values.append(choice)

Obviously this introspection is not the normal use case, but it would be sweet if it could could be compatible with ChoiceFields method. Since there is the by_name feature, I am not sure if there is a simple solution other than perhaps type checking?

ChoiceFields to_representation for reference:

def to_representation(self, value):
    if value in ('', None):
        return value
    return self.choice_strings_to_values.get(str(value), value)
...
self.choice_strings_to_values = {
    str(key): key for key in self.choices
}
oxan commented

Should be fixed with 4520ba2.