[英]Validate pydantic fields according to value in other field
I'm trying to validate some field according to other fields, example:我正在尝试根据其他字段验证某些字段,例如:
from pydantic import BaseModel, validator
class MyClass(BaseModel):
type: str
field1: Optional[str] = None
field2: Optional[str] = None
field3: Optional[str] = None
@validator("type")
def has_required_fields(cls, v, values):
required_fields {"v1": ["field1", "field3"], "v2": ["field2"]}
for required_field in required_fields[c]:
if not values[required_field]:
raise Exception
But my issue is that the values dict is empty.但我的问题是 values dict 是空的。 How should I access the other fields correctly in this situation?
在这种情况下,我应该如何正确访问其他字段?
I believe you need to set “always=True” in the validator if you plan on type being empty when you initialize it.如果您计划在初始化时类型为空,我相信您需要在验证器中设置“always=True”。 See here:
看这里:
https://github.com/pydantic/pydantic/issues/691#issuecomment-785101470 https://github.com/pydantic/pydantic/issues/691#issuecomment-785101470
Fields are validated in order they are initialized.字段按照初始化的顺序进行验证。 Dictionary is empty because there is no validated fields as the type is the first field to be validated.
字典是空的,因为没有经过验证的字段,因为类型是要验证的第一个字段。
-> Reorder the field initialization or -> Use root validator -> 重新排序字段初始化或 -> 使用根验证器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.