最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - A nested discriminated union using pydantic - Stack Overflow

programmeradmin2浏览0评论

I am writing a rest-api using FastApi. I use pydantic for data validation.

I need to make something like this work. It would be easy if I could just move disc to ReqType1 or 2 but for downwards compatiblity reasons I cannot do this. Do you know I can get a nested discriminated unitions based on type.disc to work?

from pydantic import BaseModel
from typing import Literal, Annotated, Union

class Innertype1(BaseModel):
    disc: Literal["A"]

class Inntertype2(BaseModel):
    disc: Literal["B", "C", "D"]


class ReqType1(BaseModel):
    type: Innertype1


class ReqType2(BaseModel):
    type: Inntertype2

Req = Annotated[
    Union[ReqType1, ReqType2], Field(discriminator="type.disc")
]
发布评论

评论列表(0)

  1. 暂无评论