pydantic - Cleanly initialize one model from another model without using model_dump() - Stack Overflow

Given the following toy setup:from pydantic import BaseModelclass External(BaseModel):string: strclass

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

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

Share edited Mar 11 at 7:15 DarkBee 15.5k8 gold badges72 silver badges118 bronze badges asked Mar 11 at 7:01 CoveyCovey 1391 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744810209a4595012.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信