Summary - Pydantic
- Python course
- Advanced
- Lesson 60/83
- 5 min
Combine BaseModel, Field and validator to write a user validation model.
Summary - Pydantic
In this group you learned the core concepts of Pydantic. BaseModel for model definition, Field for validation rules, field_validator for custom validation, model_config for settings, model_validate for building a model from a dict.
class User(BaseModel):
name: str = Field(min_length=2)
age: int = Field(gt=0, lt=200)
@field_validator("name")
@classmethod
def short(cls, v):
return vIn the final step you will combine all of these to write a user validation model.
Practice User validation model
Start with from pydantic import BaseModel, Field, field_validator. Define class User(BaseModel):. Add fields name: str = Field(min_length=2) and age: int = Field(gt=0, lt=200). With @field_validator("name") and @classmethod define def short(cls, v): that does return v. Create an instance with u = User(name="Ayşe", age=30). Print the values with print(u.name, u.age).
Starter code
# bring in BaseModel, Field and field_validator from pydantic
# define User class (Field rules on name and age)
# add a field_validator for name (cls and v params, return v)
# create a User instance (Ayşe, 30)
# print the valuesSample solution
from pydantic import BaseModel, Field, field_validator
class User(BaseModel):
name: str = Field(min_length=2)
age: int = Field(gt=0, lt=200)
@field_validator("name")
@classmethod
def short(cls, v):
return v
u = User(name="Ayşe", age=30)
print(u.name, u.age)Expected output
Ayşe 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one adds custom validation to a field?
- @field_validator Correct answer
- BaseModel
- Field
- model_config
Explanation: @field_validator adds custom validation to a field.
2 Match the group tools
| Term | Meaning |
|---|---|
BaseModel |
Model base |
Field |
Validation rule |
field_validator |
Custom validation |
model_validate |
Dict to model |