I know Django ninja schema uses the Pydantic model, how do I set the max/min/fixed length rules for the string field?
class TestSchema(Schema):
name1: str[length=6]
name2: str[maxlength=6]
name3: str[minlength=6]
Use constr
instead str
:
from ninja import Schema
from pydantic import constr
class TestSchema(Schema):
name1: constr(min_length=6, max_length=6)
name2: constr(max_length=6)
name3: constr(min_length=6)
1
Refer to the Oliverira’s answer. I searched the constr on the Pydantic website.
Below is the note:
This function is discouraged in favor of using Annotated with StringConstraints instead.
This function will be deprecated in Pydantic 3.0.
The suggested way:
from typing_extensions import Annotated
from pydantic import BaseModel, StringConstraints
class Foo(BaseModel):
bar: Annotated[
str,
StringConstraints(
strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$'
),
]
For my case:
name1: Annotated[
str,
StringConstraints(
min_length=6, max_length=6
),
]