[Python] A nested discriminated union using pydantic

Discussão em 'Python' iniciado por Stack, Fevereiro 7, 2025.

  1. Stack

    Stack Membro Participativo

    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")
    ]

    Continue reading...

Compartilhe esta Página