"""基础模型定义""" from datetime import datetime from typing import Optional from sqlalchemy import Column, DateTime, Integer, Boolean, func from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Mapped, mapped_column # 创建基础模型类 Base = declarative_base() class BaseModel(Base): """ 基础模型类,所有模型都应继承此类 包含通用字段:id, created_at, updated_at 时区:使用北京时间(Asia/Shanghai, UTC+8) """ __abstract__ = True __allow_unmapped__ = True # SQLAlchemy 2.0 兼容性 id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) created_at: Mapped[datetime] = mapped_column( DateTime, server_default=func.now(), nullable=False, comment="创建时间(北京时间)" ) updated_at: Mapped[datetime] = mapped_column( DateTime, server_default=func.now(), onupdate=func.now(), nullable=False, comment="更新时间(北京时间)" ) class SoftDeleteMixin: """软删除混入类""" __allow_unmapped__ = True is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) class AuditMixin: """审计字段混入类""" __allow_unmapped__ = True created_by: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) updated_by: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)