How To Validate Entries Using Pydantic Validator?
I am new to pydantic. What are some techniques I can use in Pydantic to sanitize my data and how to run proper validation checks on it? Can you please review my code and identify a
Solution 1:
code quality is better. One possible mistake in group model:
class GroupModel(BaseModel):
users: UserModel
should be
class GroupModel(BaseModel):
users: List[UserModel]
Then for simplicity I rewrote following section.
a = {'name':"james1 Wash", 'age':"23", 'streetadr':'2333 Sabrina Dr'}
b = {'name':"hh axx", 'age':"32", 'streetadr':'2333 Dr'}
u = GroupModel(users=[a, b])
This wont pass validation test for var 'a' as name contains a number. If you change that, it passes validation.
Also, you must put assigning part in a try block.
try:
u = GroupModel(users=[a, b])
except ValidationError as e:
print(e) #to see details of error. Print only if you need to see it.
Look into error handling provided in pydantic. https://pydantic-docs.helpmanual.io/usage/models/#error-handling
There are many well written examples given there. You are making good progress.
Pydantic simplifies validation. You don't need to use it if you just need some simple validation logic. But its better to use it in most real world projects were we need a lot of validation in many data classes and locations.
Post a Comment for "How To Validate Entries Using Pydantic Validator?"