pythonserializationfastapipydantic

Pydantic enum field does not get converted to string


I am trying to restrict one field in a class to an enum. However, when I try to get a dictionary out of class, it doesn't get converted to string. Instead it retains the enum. I checked pydantic documentation, but couldn't find anything relevant to my problem.

This code is representative of what I actually need.

from enum import Enum
from pydantic import BaseModel

class S(str, Enum):
    am = 'am'
    pm = 'pm'

class K(BaseModel):
    k: S
    z: str

a = K(k='am', z='rrrr')
print(a.dict()) # {'k': <S.am: 'am'>, 'z': 'rrrr'}

I'm trying to get the .dict() method to return {'k': 'am', 'z': 'rrrr'}


Solution

  • You need to use use_enum_values option of model config:

    use_enum_values

    whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialise model.dict() later (default: False)

    from enum import Enum
    from pydantic import BaseModel
    
    class S(str, Enum):
        am='am'
        pm='pm'
    
    class K(BaseModel):
        k:S
        z:str
    
        class Config:  
            use_enum_values = True  # <--
    
    a = K(k='am', z='rrrr')
    print(a.dict())