from pydantic import BaseModel, ConfigDict, Field, field_validator class VariableItemSchema(BaseModel): """单个变量-章节关联项。""" variable_name: str = Field(..., min_length=1, max_length=128, description="变量名称") chapter_names: list[str] = Field(default_factory=list, description="关联章节名称列表") checked: bool | None = Field(default=None, description="当前标注是否勾选该变量,单标注保存接口使用") @field_validator("variable_name") @classmethod def validate_required(cls, value: str) -> str: value = value.strip() if not value: raise ValueError("必填字段不能为空") return value @field_validator("chapter_names") @classmethod def validate_chapter_names(cls, values: list[str]) -> list[str]: result: list[str] = [] for value in values: chapter_name = value.strip() if not chapter_name: raise ValueError("章节名称不能为空") result.append(chapter_name) return result class VariableSaveSchema(BaseModel): """批量保存变量-章节关联。""" template_id: int = Field(..., ge=1, description="模板ID") variables: list[VariableItemSchema] = Field(default_factory=list, description="变量列表") class VariableOutSchema(BaseModel): """变量-章节关联响应模型。""" model_config = ConfigDict(from_attributes=True) id: int = Field(description="主键ID") template_id: int = Field(description="模板ID") variable_name: str = Field(description="变量名称") chapter_name: str = Field(description="章节名称") class VariableGroupOutSchema(BaseModel): """按变量分组的响应模型。""" variable_name: str = Field(description="变量名称") chapter_names: list[str] = Field(default_factory=list, description="关联章节名称列表") chapters: list[dict] = Field(default_factory=list, description="关联章节详情列表")