如何引导 FastAPI 从 Union 中选择正确的类型

How can I guide FastAPI to pick the right type type from Union

我有以下型号:

from pydantic import BaseModel

class A(BaseModel):
   tag: str
   field1: str

class B(BaseModel):
   tag: str
   field1: str
   field2: str

我正在使用它们来定义请求正文,如下所示:

@app.post('/route')
def handle(request: typing.Union[A, B])

documentation 状态:

include the most specific type first, followed by the less specific type

但我想知道是否有一种方法可以引导 FastAPI select 基于标签的正确模型。目前,我所有的模型都有一个常量标签(即类型 A 总是有 tag = 'A')。有没有一种方法可以更改我的模型定义以确保分配的模型始终与请求正文中收到的标签相匹配?

目前,我通过不输入我的 handle 函数来解决这个问题,而是专门将 tag 与模型匹配,但理想情况下我会使用 typing.Union 作为输入并确信它是正确的。

来自@rv.kvetch 的评论,将 tag 字段注释为字符串文字,例如Literal['A']表示每次都选择了正确的类型。