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] How to make a Pydantic field conditionally required based on another field?

Discussão em 'Python' iniciado por Stack, Novembro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I'm building a Pydantic model where a field's requirement depends on the value of another field.

    Specifically, I want the cpf field to be required only if the country field is set to "BR". For any other country, cpf should be optional.

    Here is my current model:

    from pydantic import BaseModel, field_validator
    from typing import Literal, Optional
    from brazilian.pydantic import CPFModel

    class User(BaseModel):
    username: str
    country: Literal["BR", "US", "PT"]
    cpf: Optional[CPFModel] = None


    My problem is that cpf is always optional. I need a validation rule that checks country and raises an error if it's "BR" and cpf is None.

    I tried using a @field_validator on cpf, but it doesn't run if the cpf field is omitted from the input data.

    What is the correct, idiomatic way in Pydantic V2 to implement this kind of cross-field validation, where one field's presence depends on another's value? I've seen @model_validator mentioned but I'm not sure how to apply it correctly for this case.

    Thanks!

    Continue reading...

Compartilhe esta Página