繁体   English   中英

Pydantic 数据类句柄 ValidationError

[英]Pydantic dataclass handle ValidationError

我正在寻找在将数据传递到 pydantic 数据类时处理 ValidationError 的解决方案。

from pydantic import BaseModel

class TestB(BaseModel):
    id: str
    price : float
    quantity : int

class TestA(BaseModel):
    orderId: str
    totalAmountPaid: float
    products: List[TestB]

data_correct_type = {"orderId": "12341234", "totalAmountPaid": 395.5,
              "products": [{"id": "abcd0001", "price": '299', "quantity": 1},
                           {"id": "abcd0002", "price": '199', "quantity": 1}]}

data_wrong_type = {"orderId": "12341234", "totalAmountPaid": 395.5,
              "products": [{"id": "abcd0001", "price": '299', "quantity": 1},
                           {"id": "abcd0002", "price": 'abc', "quantity": 1}]}

result_pydantic_1 = TestA(**data_correct_type) #works
result_pydantic_2 = TestA(**data_wrong_type) 

output:
raise 1 validation error for TestA
products -> 1 -> price
  value is not a valid float (type=type_error.float)

有什么方法可以用诸如 None 值之类的东西替换错误类型的字段? 谢谢!

代码:

from pydantic import BaseModel, validator
from typing import Union

class P(BaseModel):
    string: str
    number: Union[float, None]

    # pre=True → run before standard validators
    @validator('number', pre=True)
    def set_to_none_if_not_a_numeric(cls, v):
        try:
            return float(v)
        except ValueError:
            print('Not a number!')
            return None

a = P(**{"string": "11", "number": "12aa"})
b = P(**{"string": "11", "number": "12"})

print(a)
print('----')
print(b)

Output:

Not a number!
string='11' number=None
----
string='11' number=12.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM