[Python] Set default based on another field in pydantic BaseModel

Discussão em 'Python' iniciado por Stack, Dezembro 9, 2024.

  1. Stack

    Stack Membro Participativo

    I'd like to make the default value of the second filed in a BaseModel class dependend on the first filed + some external dictionary.

    Please, how to achieve that with Pydantic?

    Here is my naive and not working code:

    from pydantic import BaseModel

    MY_DICT: dict[str, int] = {
    "a": 1,
    "b": 2,
    }

    class MyConfig(BaseModel):
    letter: str
    plus_one_by_default_or_any_int: int = MY_DICT[letter] + 1

    Continue reading...

Compartilhe esta Página