Skip to content

Returning an Enum from a SerializerMethod #1383

@johnthagen

Description

@johnthagen

Is it possible to express this:

class Item(Model):
    name = TextField()

@unique
class Color(Enum):
    Red = "red"
    Green = "green"
    Blue = "blue"


class ItemSerializer(ModelSerializer):
    color = SerializerMethodField()

    def get_color(self, instance) -> Color:
        return Color.Red.value

    class Meta:
        model = Item
        fields = "__all__"

We've been able to use Enums directly within Models, using https://github.com/akx/django-enumfields2 and that translates properly into an OpenAPI enum.

Is there a way to expose similar functionality through a SerializerMethod in a way drf-spectacular can process?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions