Files
smart-project-pricing/后端服务/app/models/base.py
2026-01-31 21:33:06 +08:00

52 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""模型基类
包含时间戳 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"
)