Consider this FastAPI Pydantic model using a @validator decorator:
from pydantic import BaseModel, validator
class User(BaseModel):
username: str
age: int
@validator('age')
def age_must_be_adult(cls, v):
if v < 18:
raise ValueError('Must be at least 18')
return v
user = User(username='alice', age=16)What will happen when this code runs?
from pydantic import BaseModel, validator class User(BaseModel): username: str age: int @validator('age') def age_must_be_adult(cls, v): if v < 18: raise ValueError('Must be at least 18') return v user = User(username='alice', age=16)
Think about what the validator function does when the age is less than 18.
The @validator decorator runs the age_must_be_adult method when the model is created. Since age is 16, which is less than 18, the method raises a ValueError. This stops the model from being created.
You want to validate that start_date is before end_date in a Pydantic model. Which code snippet correctly implements this using @validator?
from pydantic import BaseModel, validator from datetime import date class Event(BaseModel): start_date: date end_date: date # Your validator here
Remember the validator receives the current field value and a dict of previously validated fields.
Option A correctly validates end_date by checking if start_date is already validated in values. It raises an error if end_date is not after start_date. Other options misuse parameters or try to access fields incorrectly.
Look at this Pydantic model:
from pydantic import BaseModel, validator
class Product(BaseModel):
name: str
price: float
@validator('price')
def price_positive(cls, value):
if value <= 0:
raise ValueError('Price must be positive')
product = Product(name='Book', price=0)Why does this code raise no error even though price is 0?
from pydantic import BaseModel, validator class Product(BaseModel): name: str price: float @validator('price') def price_positive(cls, value): if value <= 0: raise ValueError('Price must be positive') product = Product(name='Book', price=0)
Check what the validator function returns.
Validators must return the value after validation. Since price_positive does not return anything, it returns None implicitly, which Pydantic treats as valid. So the validation does not work as intended.
Given this Pydantic model:
from pydantic import BaseModel, validator
class User(BaseModel):
email: str
@validator('email')
def normalize_email(cls, v):
return v.lower().strip()
user = User(email=' EXAMPLE@DOMAIN.COM ')What is the value of user.email?
from pydantic import BaseModel, validator class User(BaseModel): email: str @validator('email') def normalize_email(cls, v): return v.lower().strip() user = User(email=' EXAMPLE@DOMAIN.COM ') result = user.email
Think about what lower() and strip() do to the string.
The validator converts the email to lowercase and removes spaces at the start and end. So the stored email is 'example@domain.com'.
Choose the correct statement about how the @validator decorator works in Pydantic models.
Consider the order of field validation and how values parameter works.
Validators run in the order fields are declared. They receive a values dict with already validated fields. So they can only access fields validated before them. Validators are class methods, not instance methods. Async validators are not supported automatically.