Extend a model with pydantic

18 Views Asked by At

Just started working with Pydantic models and have a question about extending existing model.

Assume that I want to put the ServiceNowEvent and ServiceNowEventModel into a package to make them available via simple imports.

The ServiceNowEvent contains key's that are always available in the event. But in different cases I want additional keys beeing available that I can define just on the fly.

class ServiceNowEvent(BaseModel):
    """ServiceNow Event Schema."""

    short_description: str
    description: str
    sys_id: str
    request: str
    ...
    

class ServiceNowEventModel(APIGatewayProxyEventModel):
    body: ServiceNowEvent

    @validator("body", pre=True)
    def transform_body_to_dict(cls, value: str) -> Any:
        return json.loads(value)

I can extend the body by simply inherting ServiceNowEvent, but then I´d need to change the type of body in ServiceNowEventModel. Like here:

class CustomServiceNowFields(ServiceNowEvent):
    my_custom_field: str


class ServiceNowEventModel(APIGatewayProxyEventModel):
    body: CustomServiceNowFields

    @validator("body", pre=True)
    def transform_body_to_dict(cls, value: str) -> Any:
        return json.loads(value)

Is there a way to keep ServiceNowEventModel untouched and directly append my_custom_field to ServiceNowEvent ?

0

There are 0 best solutions below