26

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?

funnydman
  • 9,083
  • 4
  • 40
  • 55
Ezerzez
  • 381
  • 1
  • 3
  • 3

2 Answers2

34

You can use constr:

from pydantic import BaseModel, constr

class MyPydanticModel(BaseModel):
    name: Optional[constr(max_length=10)]
ted
  • 4,791
  • 5
  • 38
  • 84
vishes_shell
  • 22,409
  • 6
  • 71
  • 81
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)
funnydman
  • 9,083
  • 4
  • 40
  • 55