如何在Pydantic V2中实现基于其他字段的条件必填?
Pydantic V2 实现依赖字段的必填性验证
要实现仅当country为"BR"时cpf字段必填的逻辑,你需要使用Pydantic V2的@model_validator(而非field_validator)——因为field_validator在字段未被传入时不会触发,而model_validator会在整个模型解析完成后执行,能覆盖所有场景。
完整实现代码
from pydantic import BaseModel, model_validator, ValidationError, PydanticCustomError from typing import Literal, Optional from brazilian.pydantic import CPFModel class User(BaseModel): username: str country: Literal["BR", "US", "PT"] cpf: Optional[CPFModel] = None @model_validator(mode='after') def validate_cpf_requirement(self) -> 'User': # 当国家为巴西且cpf未提供时触发错误 if self.country == "BR" and self.cpf is None: raise PydanticCustomError( code='missing_required_field', message='CPF is required when country is "BR"', context={'field': 'cpf'} ) return self
关键说明
mode='after'的作用:指定验证器在所有字段完成解析、默认值填充后执行,确保即使cpf字段被省略(此时self.cpf会取默认值None),验证逻辑依然能触发。- 错误关联到字段:使用
PydanticCustomError可以将错误精准关联到cpf字段,错误输出会清晰指向问题字段,比直接抛出ValueError更规范。
测试示例
合法场景
# 巴西用户提供CPF(合法) br_user = User(username="joao_silva", country="BR", cpf=CPFModel(value="987.654.321-00")) print(br_user) # 非巴西用户无需提供CPF(合法) us_user = User(username="john_doe", country="US") print(us_user)
非法场景(触发验证错误)
try: # 巴西用户未提供CPF,触发错误 invalid_br_user = User(username="maria_souza", country="BR") except ValidationError as e: print(e)
输出的错误信息会明确标记cpf字段缺失,便于调试和返回给前端。
内容的提问来源于stack exchange,提问作者Comic Hell
相关产品推荐
相关产品推荐

