Pydantic 枚举字段未转换为字符串
Pydantic enum field does not get converted to string
我试图将 class 中的一个字段限制为枚举。但是,当我尝试从 class 中获取字典时,它不会转换为字符串。相反,它保留枚举。我检查了 pydantic documentation,但找不到与我的问题相关的任何内容。
这段代码代表了我实际需要的东西。
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'}
我正在尝试将 .dict() 方法设为 return {'k': 'am', 'z': 'rrrr'}
您需要使用 model config 的 use_enum_values
选项:
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())
我试图将 class 中的一个字段限制为枚举。但是,当我尝试从 class 中获取字典时,它不会转换为字符串。相反,它保留枚举。我检查了 pydantic documentation,但找不到与我的问题相关的任何内容。
这段代码代表了我实际需要的东西。
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'}
我正在尝试将 .dict() 方法设为 return {'k': 'am', 'z': 'rrrr'}
您需要使用 model config 的 use_enum_values
选项:
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
)
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())