Files
sdb2-backend/app/models/base.py
JSC 4cec3b9d18
All checks were successful
Backend CI / lint (push) Successful in 9m21s
Backend CI / test (push) Successful in 4m0s
feat: Enhance timestamp management in BaseModel and PlaylistRepository; add automatic updates and improve code readability
2025-08-16 00:19:53 +02:00

27 lines
887 B
Python

from datetime import UTC, datetime
from typing import Any
from sqlalchemy import event
from sqlalchemy.engine import Connection
from sqlalchemy.orm import Mapper
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: Mapper[Any], connection: Connection, target: BaseModel, # noqa: ARG001
) -> None:
"""Automatically set updated_at timestamp before update operations."""
target.updated_at = datetime.now(UTC)