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.
JavaScript
x
14
14
1
from enum import Enum
2
from pydantic import BaseModel
3
4
class S(str, Enum):
5
am = 'am'
6
pm = 'pm'
7
8
class K(BaseModel):
9
k: S
10
z: str
11
12
a = K(k='am', z='rrrr')
13
print(a.dict()) # {'k': <S.am: 'am'>, 'z': 'rrrr'}
14
I’m trying to get the .dict()
method to return {'k': 'am', 'z': 'rrrr'}
Advertisement
Answer
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 serialisemodel.dict()
later (default:False
)
JavaScript
1
17
17
1
from enum import Enum
2
from pydantic import BaseModel
3
4
class S(str, Enum):
5
am='am'
6
pm='pm'
7
8
class K(BaseModel):
9
k:S
10
z:str
11
12
class Config:
13
use_enum_values = True # <--
14
15
a = K(k='am', z='rrrr')
16
print(a.dict())
17