I wanna write a nice TimestampMixin
class for my project, I hope it can:
created_at
: autonow when creation, and never change since thatupdated_at
: autonow when creationupdated_at
: auto updateupdated_at
if it is not specified when update.
like:
foo = Foo(name='foo') # created_at, updated_at autofilled
time.sleep(3)
foo.name = 'bar' # `updated_at` auto updated!
data_dict = {"name": "bar", "created_at": 1717288789, "updated_at": 1717288801}
foo_from_orm = Foo.model_validate(**data_dict) # `created_at`: 1717288789, `updated_at`: 1717288801
For now, I have no solution, I can only manually write a on_update
function and manually call it everytime when I update the model.
Is there any better solution or any ideas on this issue?
from datetime import datetime, UTC
from pydantic import BaseModel, Field
now_factory = lambda: int(datetime.now(UTC).timestamp())
class TimestampMixin(BaseModel):
created_at: int = Field(default_factory=now_factory)
updated_at: int = Field(default_factory=now_factory)
def on_update(self):
self.updated_at = now_factory()
New contributor
steveflyer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.