Can I make a default value in pydantic if None is passed in the field without using validators?

Viewed 4544

Can I make a default value in pydantic if None is passed in the field without using validators?

I have the following code, but it seems to me that the validator here is superfluous for contract_ndfl. Is there any way to do without a validator?

My code:

  class User(BaseModel):
        user: int
        s_name: str
        contract_ndfl: Optional[int]
        

       @validator('contract_ndfl')
       def set_contract_ndfl(cls, v):
           return v or 13

Wishful code:

class User(BaseModel):
      user: int
      s_name: str
      contract_ndfl: Optional[int] = 13
            
1 Answers

Maybe you can use a validator for all field and define a BaseClass for it!

class NoneDefaultModel(BaseModel):

    @validator("*", pre=True)
    def not_none(cls, v, field):
        if all(
            (
                # Cater for the occasion where field.default in (0, False)
                getattr(field, "default", None) is not None,
                v is None,
            )
        ):
            return field.default
        else:
            return v

Then you can use a Subclass to Implement your wishful code:

class Bar(NoneDefaultModel):
    bar: int = 5

Bar(bar=None)
# Bar(bar=5)
Related