When you did update_at: datetime = created_at
it did not work, because python judges created_at
at class definition time not instance creation time. They were different because basically default values are evaluated independently at instance creation time.
Solution to this could be during model creation setting updated_at
to None and then during initializing setting it as created_at
...
class User(UserBase, table=True):
id: int | None = Field(default=None, primary_key=True)
created_at: datetime = Field(default_factory=get_current_utc_time)
updated_at: datetime | None = None
last_login_at: datetime | None = None
email: EmailStr = Field(unique=True)
def __init__(self, **data):
super().__init__(**data)
if self.updated_at is None:
self.updated_at = self.created_at
The solution will solve the problem but the more maintainable solution could be create a paired factory function, something like...
inital_time_factory, shared_time_factory = create_timestamp_pair()
class User(UserBase, table=True):
id: int | None = Field(default=None, primary_key=True)
created_at: datetime = Field(default_factory=initial_time_factory)
updated_at: datetime = Field(default_factory=shared_time_factory)
last_login_at: datetime | None = None
email: EmailStr = Field(unique=True)
the create_timestamp_pair()
creates a pair of factory functions that returns the same timestamp.
Finally, I dont think validators to be the best solution, because iguess they are executed after the fields are set, not sure about this, you will have to manage validation order properly.