52 lines
1.2 KiB
Python
52 lines
1.2 KiB
Python
"""模型基类
|
||
|
||
包含时间戳 Mixin 和通用基类
|
||
遵循瑞小美数据库设计规范
|
||
"""
|
||
|
||
from datetime import datetime
|
||
|
||
from sqlalchemy import BigInteger, Integer, DateTime, func
|
||
from sqlalchemy.orm import Mapped, mapped_column
|
||
|
||
from app.database import Base
|
||
from app.config import settings
|
||
|
||
|
||
# 主键类型:SQLite 使用 Integer(支持自增),MySQL 使用 BigInteger
|
||
# SQLite 的 AUTOINCREMENT 只在 INTEGER PRIMARY KEY 时生效
|
||
_PrimaryKeyType = Integer if settings.DATABASE_URL.startswith("sqlite") else BigInteger
|
||
|
||
|
||
class TimestampMixin:
|
||
"""时间戳 Mixin"""
|
||
|
||
created_at: Mapped[datetime] = mapped_column(
|
||
DateTime,
|
||
nullable=False,
|
||
default=func.now(),
|
||
server_default=func.now(),
|
||
comment="创建时间"
|
||
)
|
||
updated_at: Mapped[datetime] = mapped_column(
|
||
DateTime,
|
||
nullable=False,
|
||
default=func.now(),
|
||
server_default=func.now(),
|
||
onupdate=func.now(),
|
||
comment="更新时间"
|
||
)
|
||
|
||
|
||
class BaseModel(Base, TimestampMixin):
|
||
"""模型基类"""
|
||
|
||
__abstract__ = True
|
||
|
||
id: Mapped[int] = mapped_column(
|
||
_PrimaryKeyType,
|
||
primary_key=True,
|
||
autoincrement=True,
|
||
comment="主键ID"
|
||
)
|