首页 > 解决方案 > 使用带有 FastApi (Pydantic) 的 List[Union[...]] 时评估模型列表中的可选字段

问题描述

给定一个带有多个响应模型的 FastAPI 端点,我希望能够根据它们的可选字段(而不是默认的必填字段)评估所有所述模型。

示例代码:

class A:
    required_field
    optional_field_A

class B:
    required_field
    optional_field_B

response_model = List[Union[A, B]]

# Given the following sample response data
raw_response_data = [
    {'required_field': 'foo_A', 'optional_field_A': 'bar_A'},
    {'required_field': 'foo_B', 'optional_field_B': 'bar_B'}
]

# Based on `response_model`, raw data will be translated to the following:
translated_data = [
    {'required_field': 'foo_A', 'optional_field_A': 'bar_A'},
    {'required_field': 'foo_B'}
]

如上所示,响应模型将仅根据必填字段评估我的模型的联合。

一个快速的肮脏技巧:
我能够通过将两个模型组合在一个 OOP 继承的联合中来解决:

class AB(A, B):
    """A synthetic union between A and B"""
    pass

# This solves my output schema
response_model = List[AB]

我对这个解决方案的问题是它有点误导,因为 API 客户端不能确定验证他们的数据来自哪个模型。(是A?还是B?)

所需的解决方案:
我想在 Pydantic 中有一个选项可以禁止在模型上设置“错误字段”,而不会破坏联合操作。换句话说,评估模型A,如果传递了错误的字段,则评估模型B。如果没有找到匹配项,则抛出错误。

标签: pythonfastapipydantic

解决方案


推荐阅读