Using Pydantic fields for validation purposes only
Recently I was stumbled upon a use case where I needed to validate Pydantic model instance using a field, but I did not require that field to be stored in the database. Basically, I needed a field for validation purpose only and did not want that field as the attribute later on.
Instead of using multiple models, the approach was to validate the model and just pop the field from the values after use.
from pydantic import BaseModel, root_validator
class TestModel(BaseModel):
is_changed: bool
check_is_changed: bool # validation field
. . .
@root_validator
def check_is_changed(self, values):
# Perform validation
. . .
del values["check_is_changed"]
return values
Here, check_is_changed is a validation field and removed after validation is completed so that it won't be available as the TestModel's attribute later on. This can also be used with a @validator decorator.
Ref:https://stackoverflow.com/questions/72425843/pydantic-basemodel-field-for-validation-purposes-only