pydantic

Cleanly initialize one model from another model without using model_dump()


Given the following toy setup:

from pydantic import BaseModel

class External(BaseModel):
    string: str

class Internal(BaseModel):
    string: str
    number: int


external_data = External(string="Hello, World!")

I would like to create an instance of Internal from external_data, but I would like to avoid the following methods:

  1. Manually setting the fields: internal_data = Internal(string=external_data.string, number=123)

  2. Dumping the values and loading them into a new instance: internal_data = Internal(**(external_data.model_dump() | {"number": 123}))

Is there a way to do this with something similar to .model_validate(external_data, from_attributes=True), avoiding what feels like an unnessecary .model_dump


Solution

  • Something like this should work:

    internal_data = Internal.model_validate(dict(external_data) | {"number": 123})
    

    Note that dict(external_data) doesn't dump the object, it only presents the fields of the object as a dictionary. All values (e.g. submodels) won't be touched. But with pydantic it is no problem to validate pydantic models. You just have to take care for this inside your (before-)validators if you make use of them.