pythonpydantic

Set default based on another field in pydantic BaseModel


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

Solution

  • You could use a pydantic validator to achieve that.

    from typing import Any, Optional, Dict
    
    from pydantic import BaseModel, root_validator
    
    class MyConfig(BaseModel):
        letter: str
        plus_one_by_default_or_any_int: int = 0
    
        @root_validator(pre=True)
        def default_val(cls, values: Dict[str, Any]):
            if values.get("plus_one_by_default_or_any_int") is None:
                values["plus_one_by_default_or_any_int"] = MY_DICT[values["letter"]] + 1
            return values