Performance: Field types and constraints
This affects the server response time and payload size by validating and serializing data efficiently before sending it to the client.
from pydantic import BaseModel, Field, EmailStr, conint class User(BaseModel): name: str = Field(..., min_length=1, max_length=50) age: conint(ge=0, le=120) # constrained int email: EmailStr # validated email
from pydantic import BaseModel class User(BaseModel): name: str age: int # no constraints email: str # no validation
| Pattern | Validation Cost | Payload Size | Server CPU Load | Verdict |
|---|---|---|---|---|
| No constraints, generic types | High (due to error handling) | Larger (unvalidated data) | High | [X] Bad |
| Specific types with constraints | Low (efficient validation) | Smaller (validated data) | Low | [OK] Good |
Field() in a Pydantic model?Field() addsField() allows adding constraints like min/max length, default values, and descriptions to model fields.Field()?min_length.min_length=3, which is correct. Others use invalid or incorrect parameters.from pydantic import BaseModel, Field
class Item(BaseModel):
price: float = Field(gt=0)
name: str = Field(min_length=2, max_length=10)
Item(price=-5, name='A')?from pydantic import BaseModel, Field
class User(BaseModel):
age: int = Field(min_length=18)
gt or ge for minimum value, not min_length.min_length on an int field causes a validation error because it applies only to strings or collections.tags field that must be a list of strings, each string at least 2 characters long. Which is the best way to enforce this using Pydantic Field()?constr can constrain strings, and conlist can constrain lists of constrained types.conlist(constr(min_length=2)) which correctly enforces each string's min length inside the list. Others either apply min_length to the list itself or incorrectly.Pass the test and this pattern moves unknown