Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":
pydantic version: 1.5.1
pydantic compiled: True
install path: /usr/local/lib/python3.8/site-packages/pydantic
python version: 3.8.5 (default, Jul 21 2020, 10:48:26) [Clang 11.0.3 (clang-1103.0.32.62)]
platform: macOS-10.15.6-x86_64-i386-64bit
optional deps. installed: ['typing-extensions']
Hi, I create a pydantic model that doesn't validate on creation, by using construct() method. But I want to validate on the object after creation, manually. How to trigger validation?
E.g.:
from pydantic import BaseModel
class OrderModel(BaseModel):
name: str
order = OrderModel.construct()
order.a_method_that_validates_the_model() # I need that function.
I tried, validate() but got TypeError: validate() takes exactly 2 positional arguments (1 given) . I looked at the codebase and seems like this is not I want? because it excepts the model as the first argument and it is a classmethod.
Hello @iedmrc
Here you go
from pydantic import BaseModel, validate_model
def validate(model: BaseModel):
*_, validation_error = validate_model(model.__class__, model.__dict__)
if validation_error:
raise validation_error
validate(order)
# pydantic.error_wrappers.ValidationError: 1 validation error for OrderModel
# name
# field required (type=value_error.missing)
If you really need to have it as a method and not a function, you could do something like this
from pydantic import BaseModel as PydanticBaseModel, validate_model
class BaseModel(PydanticBaseModel):
def check(self):
*_, validation_error = validate_model(self.__class__, self.__dict__)
if validation_error:
raise validation_error
class OrderModel(BaseModel):
name: str
order = OrderModel.construct()
order.check()
# pydantic.error_wrappers.ValidationError: 1 validation error for OrderModel
# name
# field required (type=value_error.missing)
Hope it helps !
Thanks a lot! Do you mind to add this to BaseModel itself?