pythonenumsmodelpydantic

encode Pydantic field using the Enum name instead of the value


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?


Solution

  • You are not trying to "load" anything, your problem is that you want to encode your Pydantic field using the Enum name instead of the value, when serialising your model to JSON.

    All you need to do is add a Config class to your BaseModel subclass that specifies a JSON encoder for the Group type. The json_encoders attribute is a dict keyed on type with serialiser callables:

    import enum
    from pydantic import BaseModel
    
    
    class Group(enum.Enum):
        user = 0
        manager = 1
        admin = 2
    
    
    class User(BaseModel):
        id: int
        username: str
        group: Group
    
        class Config:
            json_encoders = {Group: lambda g: g.name}
    
    
    user = User(id=5, username="admin", group=2)
    print(user)  # id=5 username='admin' group=<Group.admin: 2>
    print(user.json())  # {"id": 5, "username": "admin", "group": "admin"}