如何使用Pydantic字段指定字符串列表的约束?

0 投票
1 回答
75 浏览
提问于 2025-04-14 18:14

我想给一个字符串列表设置一些限制,这个列表至少要有1个项目,最多10个项目,而且每个字符串的长度不能超过10个字符。

我可以用constr和conlist来实现这个功能。现在我想用pydantic.Field来实现同样的功能,但似乎不太管用。

下面是示例代码:

from pydantic import (
    BaseModel,
    Field,
    conlist,
    constr,
)

# Using constr, conlist 
class FooListRequestModel(BaseModel):
    name: conlist(item_type=constr(max_length=10), min_length=1, max_length=10)
    age: int

# Using pydantic.Field
class FooListRequestModel2(BaseModel):
    name: list[str] = Field(..., min_items=1, max_items=10, max_length=10)
    age: int


if __name__ == "__main__":
    # Success validate
    fooList = FooListRequestModel(
        name=["01234567890123456789", "01234567890123456789"], age=20
    )
    print(fooList)

    # Failed to validate
    fooList2 = FooListRequestModel2(
        name=["01234567890123456789", "01234567890123456789"], age=20
    )
    print(fooList2)

1 个回答

2

这个max_length限制只适用于一个字段,也就是当你输入的是一个单独的字符串时。它并不适用于列表中的每一个项目。因此,你需要为这个有长度限制的字符串定义一个别名。下面是一个例子:

from typing import Annotated
from pydantic import BaseModel, Field


MaxLengthStr = Annotated[str, Field(max_length=10)]

# Using pydantic.Field
class FooListRequestModel2(BaseModel):
    name: list[MaxLengthStr] = Field(..., min_items=1, max_items=10)
    age: int


fooList2 = FooListRequestModel2(
    name=["01234567890123456789", "01234567890123456789"], age=20
)
print(fooList2)

这会引发:

ValidationError: 2 validation errors for FooListRequestModel2
name.0
  String should have at most 10 characters [type=string_too_long, input_value='01234567890123456789', input_type=str]
    For further information visit https://errors.pydantic.dev/2.5/v/string_too_long
name.1
  String should have at most 10 characters [type=string_too_long, input_value='01234567890123456789', input_type=str]
    For further information visit https://errors.pydantic.dev/2.5/v/string_too_long

希望这对你有帮助!

撰写回答