You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pydantic中为两个字段的组合总长度设置max_length限制

Pydantic 多字段组合总长度限制原生实现方案

你已实现单个字段的长度限制,示例代码如下:

class Email(BaseModel):
    local_part: EmailPartType[constr(max_length=255)]
    domain_part: EmailPartType[constr(max_length=255)]

针对两个字段的组合总长度限制需求,无需重写__init__方法或自定义工厂,直接使用Pydantic原生提供的模型校验器即可实现,不同版本实现方式如下:

Pydantic V2 实现(当前主流版本)

使用@model_validator装饰器定义模型级校验逻辑,设置mode='after'可在所有单字段校验完成后再执行组合校验,避免出现字段未解析完成的异常:

from pydantic import BaseModel, model_validator
from pydantic.types import constr

# 此处替换为你实际使用的EmailPartType自定义类型
EmailPartType = str

class Email(BaseModel):
    local_part: EmailPartType[constr(max_length=255)]
    domain_part: EmailPartType[constr(max_length=255)]

    @model_validator(mode='after')
    def check_total_length(self) -> "Email":
        # 若需要算上邮箱地址中@的长度,可加1,不需要则直接去掉
        total_length = len(self.local_part) + len(self.domain_part) + 1
        # 可根据实际需求修改总长度阈值,320为RFC标准规定的邮箱地址最大长度
        if total_length > 320:
            raise ValueError(f"邮箱总长度不可超过320字符,当前为{total_length}字符")
        return self

Pydantic V1 实现(旧版本兼容)

如果使用的是Pydantic V1版本,替换为@root_validator装饰器即可:

from pydantic import BaseModel, root_validator
from pydantic.types import constr

EmailPartType = str

class Email(BaseModel):
    local_part: EmailPartType[constr(max_length=255)]
    domain_part: EmailPartType[constr(max_length=255)]

    @root_validator
    def check_total_length(cls, values):
        # 优先判断两个字段是否已通过单字段校验,避免出现KeyError
        if "local_part" not in values or "domain_part" not in values:
            return values
        total_length = len(values["local_part"]) + len(values["domain_part"]) + 1
        if total_length > 320:
            raise ValueError(f"邮箱总长度不可超过320字符,当前为{total_length}字符")
        return values

补充说明

  • 校验抛出的错误信息会和普通单字段校验错误统一被Pydantic处理,无需额外适配异常捕获逻辑
  • 可根据实际业务需求调整总长度阈值,示例中的320仅为邮箱场景的参考值

内容的提问来源于stack exchange,提问作者omid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:24:03