Files
sdb2-backend/app/models/base.py
JSC b691649f7e
Some checks failed
Backend CI / lint (push) Failing after 5m0s
Backend CI / test (push) Successful in 3m46s
feat: Implement automatic updated_at timestamp management in BaseModel and update BaseRepository to reflect changes
2025-08-16 00:07:15 +02:00

22 lines
722 B
Python

from datetime import UTC, datetime
from sqlalchemy import event
from sqlmodel import Field, SQLModel
class BaseModel(SQLModel):
"""Base model with common fields for all models."""
id: int | None = Field(primary_key=True, default=None)
# 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)