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]
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With