Field Aliases
Field(alias='foo')
Field(validation_alias='foo')
Field(serialization_alias='foo')
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(alias='username')
user = User(username='johndoe')
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True))
#> {'username': 'johndoe'}
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(validation_alias='username')
user = User(username='johndoe')
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True))
#> {'name': 'johndoe'}
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(serialization_alias='username')
user = User(name='johndoe')
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True))
#> {'username': 'johndoe'}
In case you use alias
together with validation_alias
or serialization_alias
at the same time, the validation_alias
will have priority over alias
for validation, and serialization_alias
will have priority over alias
for serialization.
If you use an alias_generator
in the Model Config, you can control the order of precedence for specified field vs generated aliases via the alias_priority
setting. You can read more about alias precedence here.
使用范围
An alias is an alternative name for a field, used when serializing and deserializing data.
You can specify an alias in the following ways:
alias
on theField
must be a
str
validation_alias
on theField
can be an instance of
str
,AliasPath
, orAliasChoices
serialization_alias
on theField
must be a
str
alias_generator
on theConfig
can be a callable or an instance of
AliasGenerator
AliasPath && AliasChoices
from pydantic import BaseModel, Field, AliasPath
class User(BaseModel):
first_name: str = Field(validation_alias=AliasPath('names', 0))
last_name: str = Field(validation_alias=AliasPath('names', 1))
user = User.model_validate({'names': ['John', 'Doe']})
print(user)
#> first_name='John' last_name='Doe'
from pydantic import BaseModel, Field, AliasChoices
class User(BaseModel):
first_name: str = Field(validation_alias=AliasChoices('first_name', 'fname'))
last_name: str = Field(validation_alias=AliasChoices('last_name', 'lname'))
user = User.model_validate({'fname': 'John', 'lname': 'Doe'})
print(user)
#> first_name='John' last_name='Doe'
user = User.model_validate({'first_name': 'John', 'lname': 'Doe'})
print(user)
#> first_name='John' last_name='Doe'
from pydantic import BaseModel, Field, AliasPath, AliasChoices
class User(BaseModel):
first_name: str = Field(validation_alias=AliasChoices('first_name', AliasPath('names', 0)))
last_name: str = Field(validation_alias=AliasChoices('last_name', AliasPath('names', 1)))
user = User.model_validate({'first_name': 'John', 'last_name': 'Doe'})
print(user)
#> first_name='John' last_name='Doe'
user = User.model_validate({'names': ['John', 'Doe']})
print(user)
#> first_name='John' last_name='Doe'
user = User.model_validate({'names': ['John'], 'last_name': 'Doe'})
print(user)
#> first_name='John' last_name='Doe'
AliasGenerator
批量alias
为一组filed,生成alias
from pydantic import BaseModel, ConfigDict
class Tree(BaseModel):
model_config = ConfigDict(
alias_generator=lambda field_name: field_name.upper()
)
age: int
height: float
kind: str
t = Tree.model_validate({'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'})
print(t.model_dump(by_alias=True))
#> {'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'}
from pydantic import AliasGenerator, BaseModel, ConfigDict
class Tree(BaseModel):
model_config = ConfigDict(
alias_generator=AliasGenerator(
validation_alias=lambda field_name: field_name.upper(),
serialization_alias=lambda field_name: field_name.title(),
)
)
age: int
height: float
kind: str
t = Tree.model_validate({'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'})
print(t.model_dump(by_alias=True))
#> {'Age': 12, 'Height': 1.2, 'Kind': 'oak'}
优先级
from pydantic import BaseModel, ConfigDict, Field
def to_camel(string: str) -> str:
return ''.join(word.capitalize() for word in string.split('_'))
class Voice(BaseModel):
model_config = ConfigDict(alias_generator=to_camel)
name: str
language_code: str = Field(alias='lang')
voice = Voice(Name='Filiz', lang='tr-TR')
print(voice.language_code)
#> tr-TR
print(voice.model_dump(by_alias=True))
#> {'Name': 'Filiz', 'lang': 'tr-TR'}
alias_generator 对于 alias / validation_alias / serialization_alias的优先级管理如下
alias_priority=2
the alias will not be overridden by the alias generator.alias_priority=1
the alias will be overridden by the alias generator.alias_priority
not set:alias is set: the alias will not be overridden by the alias generator.
alias is not set: the alias will be overridden by the alias generator.
补充
# 捕获到的都是别名
print(jsonable_encoder(user))
评论区