Reputation: 686
i want to define a pydantic BaseModel with extra='forbid', and then in specific places validate objects i know will have extras, while still disallowing them if not specified - is this possible?
if not what's most concise or generally recommended approach? intermediate class? classmethod on the model? typeadaptor? utility converter function?
im interested in general, although my specific case was handling pydantic and sqlmodel objects in and out of database, with and without related models
i hoped for something like:
class NoExtras(BaseModel)
model_config = Dict(
extra='forbid',
)
name:str
somedict = dict(name='aname', extra_field='astring')
validated = NoExtras.model_validate(somedict, allow_extra=True)
Upvotes: 0
Views: 222
Reputation: 621
As of pydantic version 2.6.4, you cannot modify the behavior of extra
on a per-call basis. However, you can easily remove the extra fields from the input to achieve equivalent behavior:
validated = NoExtras.model_validate({key:value for key,value in somedict.items() if key in NoExtras.model_fields})
Be aware, this only works for flat models.
Upvotes: 0