1. 程式人生 > 其它 >pydantic學習與使用-7.欄位順序field-ordering

pydantic學習與使用-7.欄位順序field-ordering

前言

欄位順序在模型中很重要,原因如下:

  • 在定義的順序欄位中執行驗證;欄位驗證器 可以訪問較早欄位的值,但不能訪問較晚欄位的值
  • 欄位順序保留在模型模式中
  • 欄位順序保留在驗證錯誤中
  • 欄位順序由dict()和json()等儲存。

欄位順序 field-ordering

從v1.0開始,所有帶有註釋的欄位(無論是僅註釋還是帶有預設值)都將位於所有沒有註釋的欄位之前。在它們各自的組中,欄位保持它們定義的順序。

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    a: int
    b = 2
    c: int = 1
    d = 0
    e: float


print(Model.__fields__.keys())
#> dict_keys(['a', 'c', 'e', 'b', 'd'])

於是可以看到a,c,e 註釋的欄位,在沒有註釋的欄位b和d之前。

m = Model(e=2, a=1)
print(m.dict())
#> {'a': 1, 'c': 1, 'e': 2.0, 'b': 2, 'd': 0}

例項化後也是按欄位順序列印對應的dict格式

校驗失敗的時候,報錯欄位順序也是按欄位順序

try:
    Model(a='x', b='x', c='x', d='x', e='x')
except ValidationError as e:
    error_locations = [e['loc'] for e in e.errors()]

print(error_locations)
#> [('a',), ('c',), ('e',), ('b',), ('d',)]