1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Using different Pydantic models depending on the value of fields

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have 2 Pydantic models (var1 and var2). The input of the PostExample method can receive data either for the first model or the second. The use of Union helps in solving this issue, but during validation it throws errors for both the first and the second model.

    How to make it so that in case of an error in filling in the fields, validator errors are returned only for a certain model, and not for both at once? (if it helps, the models can be distinguished by the length of the field A).

    main.py

    @app.post("/PostExample")
    def postExample(request: Union[schemas.var1, schemas.var2]):

    result = post_registration_request.requsest_response()
    return result


    schemas.py

    class var1(BaseModel):
    A: str
    B: int
    C: str
    D: str


    class var2(BaseModel):
    A: str
    E: int
    F: str

    Continue reading...

Compartilhe esta Página