Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pydantic - copy object fields to another, while excluding several fields

i have a pydantic class:

class SomeData(BaseModel):
    id: int
    x: str
    y: str
    z: str

and lets say i have two object of this class, obj1, obj2.

is there any simple way, i can copy obj2, into obj1, while ignoring a subset of fields? for example copy all SomeData fields, except [id,z]

like image 618
tamirg Avatar asked May 20 '26 21:05

tamirg


1 Answers

Check out model.copy(...) (docs) and model.dict(...) (docs) - particularly the update: dict and exclude: set[str] arguments.

Given two instances(obj1 and obj2) of SomeData, update the obj1 variable with values from obj2 excluding some fields:

obj1 = SomeData(id=1, x='x', y='y', z='z')
obj2 = SomeData(id=2, x='x2', y='y2', z='z2')

obj1 = obj1.copy(update=obj2.dict(exclude={"id", "z"}))
# obj1 -> SomeData(id=1, x='x2', y='y2', z='z')

Note that this creates a new copy rather than mutate the original.


To create obj2 from obj1 excluding fields, you can directly use .copy(exclude=...):

obj1 = SomeData(id=1, x='x', y='y', z='z')

obj2 = obj1.copy(exclude={"id", "z"})
# obj2 -> SomeData(x='x', y='y')
like image 74
ccchoy Avatar answered May 22 '26 17:05

ccchoy