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)将逐字添加到字段的架构中
posted @ 2022-02-22 15:34  上海-悠悠  阅读(2699)  评论(0编辑  收藏  举报