简体   繁体   中英

How can I set max string field length constraint in Pydantic?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM