gpt4 book ai didi

python - Pydantic:验证嵌套模型

转载 作者:行者123 更新时间:2023-12-05 08:12:27 26 4
gpt4 key购买 nike

我在 Pydantic 中有一个嵌套模型。我在外部模型中有一个 root_validator 函数。我的印象是,如果调用外部根验证器,则内部模型有效。但显然不是。在下面的 MWE 中,我为内部模型提供了错误的字段名称,但外部验证器失败了:

from typing import List
from pydantic import BaseModel
from pydantic.class_validators import root_validator

class CarList(BaseModel):
cars: List[str]
colors: List[str]

class CarDealership(BaseModel):
name: str
cars: CarList

@root_validator()
def check_length(cls, v):
cars_list = v.get("cars")

if len(cars_list.cars) != len(cars_list.colors):
raise ValueError("wrong length")

return v


car_deal = {
"cars": {
"cars1": ["toyota", "tesla"],
"colors": ["white", "red"]
}
}

CarDealership.parse_obj(car_deal)

我得到的错误是:

  File "test.py", line 17, in check_length
if len(cars_list.cars) != len(cars_list.colors):
AttributeError: 'NoneType' object has no attribute 'cars'

我期待的是这样的:

pydantic.error_wrappers.ValidationError: 1 validation error for CarList
cars
field required (type=value_error.missing)

如何确保首先验证内部模型?

最佳答案

更新:外部类版本的验证

from typing import List
from pydantic import BaseModel
from pydantic.class_validators import root_validator


class CarList(BaseModel):
cars: List[str]
colors: List[str]


class CarDealership(BaseModel):
name: str
cars_list: CarList

@root_validator(pre=True)
def check_length(cls, v):
cars_list = v.get("cars_list")

if not cars_list:
return v
cars = cars_list.get("cars")
colors = cars_list.get("colors")
if not isinstance(cars, list) or not isinstance(colors, list):
return v
if cars is not None and colors is not None and len(cars) != len(colors):
raise ValueError("wrong length")

return v

root_validator 默认 pre=False,内部模型已经验证,所以你得到了 v == {}

可以在CarList中做check_length,检查carscolors是否存在(它们有已经验证,如果失败则为 None)。

from typing import List
from pydantic import BaseModel
from pydantic.class_validators import root_validator


class CarList(BaseModel):
cars: List[str]
colors: List[str]

@root_validator
def check_length(cls, v):
cars = v.get("cars")
colors = v.get("colors")

if cars is not None and colors is not None and len(cars) != len(colors):
raise ValueError("wrong length")

return v


class CarDealership(BaseModel):
name: str
car_list: CarList


car_deal_1 = {
"name": "value",
"car_list": {
"cars1": ["toyota", "tesla"],
"colors": ["white", "red"]
}
}

CarDealership.parse_obj(car_deal_1)
# pydantic.error_wrappers.ValidationError: 1 validation error for CarDealership
# car_list -> cars
# field required (type=value_error.missing)

car_deal_2 = {
"name": "value",
"car_list": {
"cars": ["toyota", "tesla"],
"colors": ["white", "red", "bule"]
}
}

CarDealership.parse_obj(car_deal_2)
# pydantic.error_wrappers.ValidationError: 1 validation error for CarDealership
# car_list -> __root__
# wrong length (type=value_error)

关于python - Pydantic:验证嵌套模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68082983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com