Pydantic aliases#
Aliased fields#
pydantic
library allows to set the alias for a field that is used during serialization/deserialization
instead of the field name. pydantic-xml
respects field aliases too:
Model
class Company(BaseXmlModel, tag='company'):
title: str = attr(alias='trade-name')
website: HttpUrl = element(alias='web-site')
Document
<company trade-name="SpaceX">
<web-site>https://www.spacex.com</web-site>
</company>
{
"trade-name": "SpaceX",
"web-site": "https://www.spacex.com"
}
Template models#
pydantic
aliases make it possible to declare so-called template models.
The base model implements the data-validation and data-processing logic but
the fields mapping is described in the inherited classes:
Model
class VehicleTemplate(BaseXmlModel):
drivers: int = attr()
title: str = attr()
engine: str = element()
class Car(VehicleTemplate, tag='car'):
model_config = pd.ConfigDict(
alias_generator=lambda field: {'title': 'make', 'engine': 'motor'}.get(field, field),
)
class Airplane(VehicleTemplate, tag='airplane'):
model_config = pd.ConfigDict(
alias_generator=lambda field: {'drivers': 'pilots', 'title': 'model'}.get(field, field),
)
class Vehicles(BaseXmlModel, tag='vehicles'):
items: List[Union[Car, Airplane]]
Document
<vehicles>
<car make="Ford Mustang" drivers="1">
<motor>Coyote V8</motor>
</car>
<airplane model="Bombardier Global 7500" pilots="2">
<engine>General Electric Passport</engine>
</airplane>
<car make="Audi A8" drivers="1">
<motor>V8</motor>
</car>
</vehicles>
{
"items": [
{
"make": "Ford Mustang",
"drivers": 1,
"motor": "Coyote V8"
},
{
"model": "Bombardier Global 7500",
"pilots": 2,
"engine": "General Electric Passport"
},
{
"make": "Audi A8",
"drivers": 1,
"motor": "V8"
}
]
}