你可以使用受歧视的工会 https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions(感谢 @larsks 在评论中提到这一点)。建立一个受歧视的工会,“验证速度更快,因为仅尝试针对一种模型”, 也“如果失败,只会出现一个明确的错误”。下面的工作示例:
app.py
import schemas
from fastapi import FastAPI, Body
from typing import Union
app = FastAPI()
@app.post("/")
def submit(item: Union[schemas.Model1, schemas.Model2] = Body(..., discriminator='model_type')):
return item
模式.py
from typing import Literal
from pydantic import BaseModel
class Model1(BaseModel):
model_type: Literal['m1']
A: str
B: int
C: str
D: str
class Model2(BaseModel):
model_type: Literal['m2']
A: str
E: int
F: str
测试输入 - 输出
#1 Successful Response #2 Validation error #3 Validation error
# Request body # Request body # Request body
{ { {
"model_type": "m1", "model_type": "m1", "model_type": "m2",
"A": "string", "A": "string", "A": "string",
"B": 0, "C": "string", "C": "string",
"C": "string", "D": "string" "D": "string"
"D": "string" } }
}
# Server response # Server response # Server response
200 { {
"detail": [ "detail": [
{ {
"loc": [ "loc": [
"body", "body",
"Model1", "Model2",
"B" "E"
], ],
"msg": "field required", "msg": "field required",
"type": "value_error.missing" "type": "value_error.missing"
} },
] {
} "loc": [
"body",
"Model2",
"F"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
另一种方法是尝试解析模型(基于您作为查询/路径参数传递的鉴别器),如上所述这里(更新1) https://stackoverflow.com/a/71228281/17865804.