How to track mutations in models objects? #2600
-
Hi, I need to track the mutations in a model object. class User(BaseModel):
id: int
name: str
user = User(1, "John Doe")
user.name = "John Peter" # Here ∆ = {"name": ("John Doe", "John Peter")}
user.id = 3 # Here ∆ = {"id": (1, 3), "name": ("John Doe", "John Peter")}
user(id = 4, name = "Elton") # Here ∆ = {"id": (3, 4), "name": ("John Peter", "Elton")}
Is there any way to track this in |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi @balukrishnans from pydantic import BaseModel
class User(BaseModel, underscore_attrs_are_private = True):
id: int
name: str
_modifs: dict[str, tuple[object, object]] = {}
def __setattr__(self, key, value):
old_value = self.__dict__.get(key)
super().__setattr__(key, value)
self._modifs[key] = (old_value, value)
user = User(id=1, name="John Doe")
user.name = "John Peter" # Here ∆ = {"name": ("John Doe", "John Peter")}
assert user._modifs == {'name': ('John Doe', 'John Peter')}
user.id = 3 # Here ∆ = {"id": (1, 3), "name": ("John Doe", "John Peter")}
assert user._modifs == {'name': ('John Doe', 'John Peter'), 'id': (1, 3)} ? |
Beta Was this translation helpful? Give feedback.
-
I implemented a serializable way to get mutations needed (diff) between two instances here, if someone needs something like that. It outputs a list of mutations, and a way to apply them. |
Beta Was this translation helpful? Give feedback.
Hi @balukrishnans
Something like this
?