# class ProcessStepCreate(BaseModel):
# process_flow_id: int = Field(examples=[1])
# name: str = Field(examples=["工艺步骤名称"])
# description: str = Field(examples=["工艺步骤描述"])
# order: int = Field(examples=[1])
# parameter_requirements: dict = Field(examples={})
# equipment_requirements: dict = Field(examples={})
# model_config = ConfigDict(from_attributes=True)
# class ProcessStepUpdate(BaseModel):
# id: int
# process_flow_id: int = Field(examples=[1])
# name: str = Field(examples=["工艺步骤名称"])
# description: str = Field(examples=["工艺步骤描述"])
# order: int = Field(examples=[1])
# parameter_requirements: dict = Field(examples={})
# equipment_requirements: dict = Field(examples={})
# model_config = ConfigDict(from_attributes=True)
class ProcessStepCreate(BaseModel):
process_flow_id: int = Field(..., description="工艺流程ID")
name: str = Field(..., description="步骤名称")
description: str = Field(..., description="步骤描述")
order: int = Field(..., description="步骤顺序")
parameter_requirements: dict = Field({}, description="参数要求")
equipment_requirements: dict = Field({}, description="设备要求")
class ProcessStepUpdate(BaseModel):
id: int = Field(..., description="工艺步骤ID")
process_flow_id: int = Field(..., description="工艺流程ID")
name: str = Field(..., description="步骤名称")
description: str = Field(..., description="步骤描述")
order: int = Field(..., description="步骤顺序")
parameter_requirements: dict = Field({}, description="参数要求")
equipment_requirements: dict = Field({}, description="设备要求")
#注释掉的代码是有问题的,下面对应的新代码是可以运行的。
1. 真正的错误原因
-
Pydantic 语法错误:
原代码中Field(examples={})
的写法错误,因为examples
参数应接受一个列表(如examples=[{"key": "value"}]
),而用户误将字典直接赋值给examples
。
示例:# 错误写法 ❌ material_records: dict = Field(examples={}) # 正确写法 ✅ material_records: dict = Field(examples=[{}]) # 示例值为包含空字典的列表
-
字段必填性:
原代码未设置默认值(如Field(examples=[{}])
),导致material_records
等字段为必填。若请求中未传递这些字段,会触发验证错误。
修改后的代码通过Field({}, ...)
设置默认空字典,使字段变为可选,避免了必填问题。
2. 用户解决方案的合理性
-
避免
examples
参数语法错误:
将examples
替换为description
,绕过了错误的examples
用法,同时提升文档可读性。 -
设置默认值解决必填性:
通过Field({}, ...)
使字段可选,避免请求中遗漏导致的错误。
修正后的完整总结
错误根源
-
examples
参数语法错误:
Field(examples={})
应改为Field(examples=[{}])
,因为examples
需要列表格式。 -
字段必填性:
未设置默认值的字段导致 OpenAPI 文档生成时认为它们是必填项,而实际业务中可能允许为空。
正确解决方案
- 修正
examples
参数:# 原错误代码 material_records: dict = Field(examples={}) # 修正后 material_records: dict = Field(default={}, examples=[{}], description="物料记录")
- 设置合理的默认值:
material_records: dict = Field(default={}, description="物料记录")