Envops
Envops

Reputation: 23

Dynamic default value from a different Pydantic model

Example code:

class MyModel(BaseModel):
    name: str = "examplename"

class MySecondModel(BaseModel):
    derivedname: Optional[str]
    @validator('derivedname')
    def default_name(cls, v, *, values, **kwargs):
        return v or values[MyModel.name]  # psuedocode, doesn't work

I know this works when the field is in the same class, and have no issues with that. However I'd like to give a default value based on a field in an instance of a different pydantic model.

Of course I could just take the model in my code and programmatically do this, but I'd like to avoid that for quite obvious reasons.

Is this possible or am I wasting my time?

Upvotes: 0

Views: 1483

Answers (1)

alex_noname
alex_noname

Reputation: 32283

This is uncommon, but you could save the related model object as private class variable and use it in the validator.

class MyModel(BaseModel):
    name: str = "examplename"

class MySecondModel(BaseModel):
    derivedname: Optional[str]
    _my_model: ClassVar[MyModel] = MyModel()

    @validator('derivedname')
    def default_name(cls, v, *, values, **kwargs):
        return v or cls._my_model.name

Upvotes: 2

Related Questions