[Python] encode Pydantic field using the Enum name instead of the value

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Enum class:

    class Group(enum.Enum):
    user = 0
    manager = 1
    admin = 2


    I have a pydantic model:

    class User(BaseModel):
    id: int
    username: str
    group: Group


    It generated serialised to json following:

    {
    "id": 5,
    "username": "admin",
    "group": 2
    }


    However, I would like to get the name of the enum field instead of its value, so it should be:

    {
    "id": 5,
    "username": "admin",
    "group": "admin"
    }


    Is this possible at all? If so, how?

    Continue reading...

Compartilhe esta Página