Having the following object
{'d': {'results': [
{'superHeroPublicId': '1',
'power': '100.00',
'infoText': 'irrelevant'},
{
'SuperHeroPublicId': '2',
'Power': '1541.60',
'InfoText': 'irrelevant'} ]}}
And the following customization of the pydantic’s BaseModel
class ApiPublicBaseModel(BaseModel):
class Config:
alias_generator = camelize
allow_population_by_field_name = True
extra = Extra.ignore
json_encoders = {
datetime: lambda value: value.isoformat(),
}
Assuming that I can’t change the ApiPublicBaseModel written in pydantic v1, how can I create a model that doesn’t crash when I try to validate objects? This camelCase / PascalCase is driving me crazy.
A few approaches here:
- Create a
root_validator
withpre=True
to manipulate the json object before the model is instantiated. - (If you can’t add validators to the model) Create multiple class definitions and validate using a
union
For the 1st option:
from pydantic import BaseModel, Field, root_validator
class ApiPublicBaseModel(BaseModel):
class Config:
allow_population_by_field_name = True
...
@root_validator(pre=True)
def coerce_casing(cls, values):
if "SuperHeroPublicId" in values:
values["superHeroPublicId"] = values.pop("SuperHeroPublicId")
return values
2nd option is a bit wonky in V1 (much neater in V2 with discriminated union):
class ApiPublicBaseModel1(BaseModel):
super_hero_public_id: str = Field(alias="superHeroPublicId")
class ApiPublicBaseModel2(BaseModel):
super_hero_public_id: str = Field(alias="SuperHeroPublicId")
class AnotherModel(BaseModel):
__root__: Union[ApiPublicBaseModel1, ApiPublicBaseModel2]
m1 = AnotherModel.parse_obj(dict(superHeroPublicId="foo"))
m2 = AnotherModel.parse_obj(dict(SuperHeroPublicId="foo"))
assert m1.__root__ == m2.__root__