refactor(backend): adopt typed SQLAlchemy models

This commit is contained in:
2026-05-04 22:05:33 +08:00
parent d811c20932
commit f939a50950
9 changed files with 129 additions and 71 deletions
+23 -12
View File
@@ -1,6 +1,11 @@
from sqlalchemy import Column, Integer, String, Boolean, Text, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from __future__ import annotations
from datetime import datetime
from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func
from backend.models.database import Base
@@ -9,27 +14,33 @@ class TaskTemplate(Base):
__tablename__ = "task_templates"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
name = Column(String(100), nullable=False, comment="模板名称")
description = Column(Text, nullable=True, comment="模板描述")
id: Mapped[int] = mapped_column(primary_key=True, index=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(100), nullable=False, comment="模板名称")
description: Mapped[str | None] = mapped_column(Text, nullable=True, comment="模板描述")
# 父模板 ID(用于继承)
parent_id = Column(
Integer,
parent_id: Mapped[int | None] = mapped_column(
ForeignKey("task_templates.id", ondelete="SET NULL"),
nullable=True,
comment="父模板 ID",
)
# 字段配置(JSON 格式)
field_config = Column(Text, nullable=False, comment="字段配置(JSON")
field_config: Mapped[str] = mapped_column(Text, nullable=False, comment="字段配置(JSON")
is_active = Column(Boolean, default=True, comment="是否启用")
created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment="更新时间")
is_active: Mapped[bool] = mapped_column(Boolean, default=True, comment="是否启用")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), comment="创建时间"
)
updated_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), onupdate=func.now(), comment="更新时间"
)
# 自引用关系:父模板和子模板
parent = relationship("TaskTemplate", remote_side=[id], backref="children")
parent: Mapped[TaskTemplate | None] = relationship(
remote_side="TaskTemplate.id", back_populates="children"
)
children: Mapped[list[TaskTemplate]] = relationship(back_populates="parent")
def __repr__(self):
return f"<TaskTemplate(id={self.id}, name='{self.name}', is_active={self.is_active})>"