python type_error ai_generated true

Pydantic 验证错误:ResponseModel 的字段不是有效的字典。

pydantic.error_wrappers.ValidationError: 1 validation error for ResponseModel value is not a valid dict

ID: python/fastapi-response-model-mismatch

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2024-05-12首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

响应模型期望字典,但函数返回了其他类型(如列表或字符串)。

English

Response model expects a dict but function returns a different type (e.g., list or string).

generic

解决方案

  1. 95% 成功率
    Ensure return type matches response_model: @app.get('/item', response_model=Item)
    async def get_item() -> Item:
        return Item(name='test', price=10.0)
  2. 85% 成功率
    Use response_model_exclude_unset=True to allow missing fields: @app.get('/item', response_model=Item, response_model_exclude_unset=True)

无效尝试

常见但无效的做法:

  1. 60% 失败

    Loses type safety and may cause runtime errors downstream.

  2. 70% 失败

    May not match model fields exactly; still validation error.