inspector00
inspector00

Reputation: 3

can pydantic validate fields on update while still using optional fields that are not provided to the constructor

I have a simple pydantic class with 1 optional field and one required field with a constraint. I'd like to ensure the constraint item is validated on both create and update while keeping the Optional field optional.

If I don't use the MyConfig dataclass attribute with a validate_assignment attribute true, I can create the item with no table_key attribute but the s3_target.target = 'BadPath' line of code is allowed. If I don't include the dataclass attribute then I don't have to provide a table_key upon creation but the s3_target update line is allowed to run.

Is there any way to easily make pydantic support both scenarios?

from pydantic.dataclasses import dataclass
from pydantic import BaseModel, constr

from pydantic.class_validators import Optional

class MyConfig:
    validate_assignment = True


@dataclass(config=MyConfig)
class S3Target(BaseModel):
    table_key: Optional[str] = None
    # target: str = Field(regex=r'^s3://([^/]+)/(.*?([^/]+))/$', description="must be a valid s3 path", )
    target: constr(regex=r'^s3://([^/]+)/(.*?([^/]+))/$')


s3_target = S3Target(target='s3://bucket/location/')
s3_target.target = 'BadPath'

I tried adding the dataclass with validate_assignment=true and expected the Optional Field to stay optional and not have to pass this into the S3Target constructor. I tried to set validate_assignment to False and it also did not allow the item to be created without a table_key.

Upvotes: 0

Views: 980

Answers (1)

cstoltze
cstoltze

Reputation: 906

Pydantic supports validating on assignment through the validate_assignment option on its ModelConfig class. Set it to True for the desired behavior.

class S3Target(BaseModel):
    table_key: Optional[str] = None
    # target: str = Field(regex=r'^s3://([^/]+)/(.*?([^/]+))/$', description="must be a valid s3 path", )
    target: constr(regex=r'^s3://([^/]+)/(.*?([^/]+))/$')

    class Config:
        validate_assignment = True

There's no need to use a dataclass decorator to achieve this behavior. (And I don't know how to get this behavior while using the dataclass decorator)

Upvotes: 0

Related Questions