簡體   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