You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Yes, you can just use .model_validate() without any arguments and it works for many built-in types (i.e. bytes).
But problems can be faced with user-defined types (with __get_pydantic_core_schema__ defined):
class SomeValidator:
def create_with_info(self, base_data: Any, info: core_schema.ValidationInfo) -> SomeUserDefinedType:
if info.mode == 'json':
... # one validation
elif info.mode == 'python':
... # another validation
def __get_pydantic_core_schema__(self, _source_type: Any, _handler: GetCoreSchemaHandler):
validations = [
core_schema.with_info_plain_validator_function(self.create_with_info),
...
]
...
return core_schema.chain_schema(validations)
MyType = Annotated[SomeUserDefinedType, SomeValidator(...)]
class MyModel(BaseModel):
a: MyType
MyModel.model_validate_json(json_string) # works nicely with validating directly from json string, `info.mode=='json'`
MyModel.model_validate(jsonable_dict) # unfortunately, always `info.mode=='python'`
Is it by design? Could mode='json' be added to model_validate() in the next versions of Pydantic?
I think this is definitely a reasonable feature request. Given that this is discussed already in #9009, I'm going to close this as a duplicate, but it will good to have this issue as a reference when #9009 is being worked on!
Initial Checks
Description
BaseModel
'smodel_dump
method allows to dump model to jsonable container (not to json string), usingmode='json'
:This gives nice jsonable dict.
But there is no symmetrical
mode='json'
argument toMyModel.model_validate(...)
function:Yes, you can just use
.model_validate()
without any arguments and it works for many built-in types (i.e.bytes
).But problems can be faced with user-defined types (with
__get_pydantic_core_schema__
defined):Is it by design? Could
mode='json'
be added tomodel_validate()
in the next versions of Pydantic?Affected Components
.model_dump()
and.model_dump_json()
model_construct()
, pickling, private attributes, ORM modeThe text was updated successfully, but these errors were encountered: