feat: Implement automatic updated_at timestamp management in BaseModel and update BaseRepository to reflect changes
Some checks failed
Backend CI / lint (push) Failing after 5m0s
Backend CI / test (push) Successful in 3m46s

This commit is contained in:
JSC
2025-08-16 00:07:15 +02:00
parent 87d6e6ed67
commit b691649f7e
2 changed files with 9 additions and 0 deletions

View File

@@ -1,5 +1,6 @@
from datetime import UTC, datetime
from sqlalchemy import event
from sqlmodel import Field, SQLModel
@@ -11,3 +12,10 @@ class BaseModel(SQLModel):
# timestamps
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
# SQLAlchemy event listener to automatically update updated_at timestamp
@event.listens_for(BaseModel, "before_update", propagate=True)
def update_timestamp(mapper, connection, target):
"""Automatically set updated_at timestamp before update operations."""
target.updated_at = datetime.now(UTC)

View File

@@ -114,6 +114,7 @@ class BaseRepository[ModelType]:
for field, value in update_data.items():
setattr(entity, field, value)
# The updated_at timestamp will be automatically set by the SQLAlchemy event listener
self.session.add(entity)
await self.session.commit()
await self.session.refresh(entity)