pydantic學習與使用-12.使用 Field 定制字段


前言

Field 可用於提供有關字段和驗證的額外信息,如設置必填項和可選,設置最大值和最小值,字符串長度等限制

Field模塊

關於 Field 字段參數說明

  • Field(None) 是可選字段,不傳的時候值默認為None
  • Field(...) 是設置必填項字段
  • title 自定義標題,如果沒有默認就是字段屬性的值
  • description 定義字段描述內容
from pydantic import BaseModel, Field


class Item(BaseModel):
    name: str
    description: str = Field(None,
                             title="The description of the item",
                             max_length=10)
    price: float = Field(...,
                         gt=0,
                         description="The price must be greater than zero")
    tax: float = None


a = Item(name="yo yo",
         price=22.0,
         tax=0.9)
print(a.dict())  # {'name': 'yo yo', 'description': None, 'price': 22.0, 'tax': 0.9}

schema_json

title 和 description 在 schema_json 輸出的時候可以看到

print(Item.schema_json(indent=2))

"""
{
  "title": "Item",
  "type": "object",
  "properties": {
    "name": {
      "title": "Name",
      "type": "string"
    },
    "description": {
      "title": "The description of the item",
      "maxLength": 10,
      "type": "string"
    },
    "price": {
      "title": "Price",
      "description": "The price must be greater than zero",
      "exclusiveMinimum": 0,
      "type": "number"
    },
    "tax": {
      "title": "Tax",
      "type": "number"
    }
  },
  "required": [
    "name",
    "price"
  ]
}
"""

Field 相關參數

Field可用於提供有關字段和驗證的額外信息。

參數名稱 描述
default (位置參數)字段的默認值。由於Field替換了字段的默認值,因此第一個參數可用於設置默認值。使用省略號 ( ...) 表示該字段為必填項。
default_factory 當該字段需要默認值時將被調用。除其他目的外,這可用於設置動態默認值。禁止同時設置default和default_factory。
alias 字段的別名
description 文檔字符串
exclude 在轉儲(.dict和.json)實例時排除此字段
include 在轉儲(.dict和.json)實例時(僅)包含此字段
const 此參數必須與字段的默認值相同(如果存在)
gt 對於數值 ( int, float, ),向 JSON SchemaDecimal添加“大於”的驗證和注釋exclusiveMinimum
ge 對於數值,這將添加“大於或等於”的驗證和minimumJSON 模式的注釋
lt 對於數值,這會為exclusiveMaximumJSON Schema添加“小於”的驗證和注釋
le 對於數值,這將添加“小於或等於”的驗證和maximumJSON 模式的注釋
multiple_of 對於數值,這會multipleOf向 JSON Schema添加“多個”的驗證和注釋
max_digits 對於Decimal值,這將添加驗證以在小數點內具有最大位數。它不包括小數點前的零或尾隨的小數零。
decimal_places 對於Decimal值,這增加了一個驗證,最多允許小數位數。它不包括尾隨十進制零。
min_itemsminItems 對於列表值,這會向 JSON Schema添加相應的驗證和注釋
max_itemsmaxItems 對於列表值,這會向 JSON Schema添加相應的驗證和注釋
unique_itemsuniqueItems 對於列表值,這會向 JSON Schema添加相應的驗證和注釋
min_lengthminLength 對於字符串值,這會向 JSON Schema添加相應的驗證和注釋
max_lengthmaxLength 對於字符串值,這會向 JSON Schema添加相應的驗證和注釋
allow_mutation 一個布爾值,默認為True. TypeError當為 False 時,如果在實例上分配了字段,則該字段引發 a 。模型配置必須設置validate_assignment為True執行此檢查。
regex 對於字符串值,這會添加從傳遞的字符串生成的正則表達式驗證和patternJSON 模式的注釋
repr 一個布爾值,默認為True. 當為 False 時,該字段應從對象表示中隱藏。
** 任何其他關鍵字參數(例如examples)將逐字添加到字段的架構中


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM