如何控制Pydantic生成的字段标签事例



我有以下pydantic模型:

import pydantic
class Creator(pydantic.BaseModel):
firstName: str = None
lastName: str = None
middle_name: str = None

CCD_ 1的输出为

{
"title": "Creator",
"type": "object",
"properties": {
"firstName": {
"title": "Firstname",
"type": "string"
},
"lastName": {
"title": "Lastname",
"type": "string"
},
"middle_name": {
"title": "Middle Name",
"type": "string"
}
}
}

字段标签(字段规范中的"title"属性,而不是主标题(具有标题大小写。但是,只有下划线分隔的属性才会拆分为组件。我如何控制生成";标题";属性?

这是在回答你的问题吗?
import pydantic
class SampleModel(pydantic.BaseModel):
firstName: str = pydantic.Field(
None,
title='First Name',
description='the first name'
)
middle_name: str = pydantic.Field(
None,
title='Middle Name',
description='the middle name' 
)
print(SampleModel.schema_json(indent=2))
{
"title": "SampleModel",
"type": "object",
"properties": {
"firstName": {
"title": "First Name",
"description": "the first name",
"type": "string"
},
"middle_name": {
"title": "Middle Name",
"description": "the middle name",
"type": "string"
}
}
}

如果您想自动生成title,您可以使用子类Config:

import pydantic
class SampleModel(pydantic.BaseModel):
class Config:
@staticmethod
def schema_extra(schema, model):
for name, prop in schema.get('properties', {}).items():
prop['title'] = name.upper()
firstName: str = None
middle_name: str = None
print(SampleModel.schema_json(indent=2))
{
"title": "SampleModel",
"type": "object",
"properties": {
"firstName": {
"title": "FIRSTNAME",
"type": "string"
},
"middle_name": {
"title": "MIDDLE_NAME",
"type": "string"
}
}
}

相关内容

  • 没有找到相关文章