I'm working with an API where the schema for creating a group is effectively:
class Group(BaseModel):
identifier: str
I was hoping I could do this instead:
class Group(BaseModel):
groupname: str = Field(..., alias='identifier')
But with that configuration it's not possible to set the attribute value using the name groupname
. That is, running this fails with a field required
error:
>>> g = Group(groupname='foo')
pydantic.error_wrappers.ValidationError: 1 validation error for Group
identifier
field required (type=value_error.missing)
Is it is possible to use either the alias or the actual attribute name to set the attribute value? I was hoping that these two would be equivalent:
>>> Group(identifier='foo')
>>> Group(groupname='foo')
Maybe you are looking for the 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')))
Output:
Group(groupname='foo')
Group(groupname='bar')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.