我可以使用 "unaliased" 属性名称初始化 pydantic 模型吗?
Can I initialize a pydantic model using the "unaliased" attribute name?
我正在使用一个 API,其中用于创建群组的架构有效:
class Group(BaseModel):
identifier: str
我希望我可以这样做:
class Group(BaseModel):
groupname: str = Field(..., alias='identifier')
但是使用该配置无法使用名称 groupname
设置属性值。也就是说,运行 失败并出现 field required
错误:
>>> g = Group(groupname='foo')
pydantic.error_wrappers.ValidationError: 1 validation error for Group
identifier
field required (type=value_error.missing)
是否可以使用别名或实际属性名称来设置属性值?我希望这两个是等价的:
>>> Group(identifier='foo')
>>> Group(groupname='foo')
也许您正在寻找 allow_population_by_field_name
config option:
whether an aliased field may be populated by its name as given by the model attribute, as well as the alias (default: False
)
from pydantic import BaseModel, Field
class Group(BaseModel):
groupname: str = Field(..., alias='identifier')
class Config:
allow_population_by_field_name = True
print(repr(Group(identifier='foo')))
print(repr(Group(groupname='bar')))
输出:
Group(groupname='foo')
Group(groupname='bar')
我正在使用一个 API,其中用于创建群组的架构有效:
class Group(BaseModel):
identifier: str
我希望我可以这样做:
class Group(BaseModel):
groupname: str = Field(..., alias='identifier')
但是使用该配置无法使用名称 groupname
设置属性值。也就是说,运行 失败并出现 field required
错误:
>>> g = Group(groupname='foo')
pydantic.error_wrappers.ValidationError: 1 validation error for Group
identifier
field required (type=value_error.missing)
是否可以使用别名或实际属性名称来设置属性值?我希望这两个是等价的:
>>> Group(identifier='foo')
>>> Group(groupname='foo')
也许您正在寻找 allow_population_by_field_name
config option:
whether an aliased field may be populated by its name as given by the model attribute, as well as the alias (default:
False
)
from pydantic import BaseModel, Field
class Group(BaseModel):
groupname: str = Field(..., alias='identifier')
class Config:
allow_population_by_field_name = True
print(repr(Group(identifier='foo')))
print(repr(Group(groupname='bar')))
输出:
Group(groupname='foo')
Group(groupname='bar')