Reputation: 117
I have json, from external system, with fields like 'system-ip', 'domain-id'. those name are not allowed in python, so i want to change them to 'system_ip', 'domain_id' etc. I read all on stackoverflow with 'pydantic' w keywords, i tried examples from pydantic docs, as a last resort i generated json schema from my json, and then with
datamodel-codegen --input device_schema.json --output model.py
i generated model.
generated model has fields like
system_ip: str = Field(..., alias='system-ip')
host_name: str = Field(..., alias='host-name')
device_type: str = Field(..., alias='device-type')
device_groups: List[str] = Field(..., alias='device-groups')
and it still doesn't work . when i do
with open("device.json") as file:
raw_device = json.load(file)
d = PydanticDevice(**raw_device)
pydantic still sees the 'old' field names, not the annotated, and i have error
TypeError: __init__() got an unexpected keyword argument 'system-ip'
What i do wrong?
Upvotes: 3
Views: 3570
Reputation: 117
so, for future reference, decorator @pydantic.dataclass doesn't do the same thing as inherit from pydantic BaseModel
@dataclasses
class VmanageDevice:
deviceId: str
system_ip: str = Field(..., alias='system-ip')
host_name: str = Field(..., alias='host-name')
...
doesn't work
but
class VmanageDevice(BaseModel):
deviceId: str
system_ip: str = Field(..., alias='system-ip')
host_name: str = Field(..., alias='host-name')
reachability: str
...
works as charm
Upvotes: 6