So, I have pydantic model with a string field:
class MyPydanticModel(BaseModel):
name: Optional[str]
And I want to set the max length for this field to 10. How can I do this?
You can use constr
:
from pydantic import BaseModel, constr
class MyPydanticModel(BaseModel):
name: Optional[constr(max_length=10)]
You can also use Field
, it has support for constraints too, for example:
If field is optional:
from pydantic import BaseModel, Field
from typing import Optional
class MyPydanticModel(BaseModel):
title: Optional[str] = Field(None, max_length=10)
If field is required:
from pydantic import BaseModel, Field
from typing import Optional
class MyPydanticModel(BaseModel):
title: str = Field(..., max_length=10)