首页 > 解决方案 > 如何将 Pydantic 基本模式用于 n 个子模式

问题描述

我是 pydantic 的新手,我想以 JSONAPI 标准的形式为下面的 python 字典定义 pydantic 模式和字段

{
  "data": {
    "type": "string",
    "attributes":{
           "title": "string",
           "name": "string"
          }
}

我设法通过定义多个模式来实现这一点,如下所示,

class Child2(BaseModel):
    title: str
    name: str

class Child1(BaseModel):
    type: str
    attributes: Child2

class BaseParent(BaseModel):
    data: Child1

但是,我将有多个具有相同 json API 结构的 json 请求,如下所示,

example 1 {
  "data": {
    "type": "string",
    "attributes":{
           "source": "001",
           "status": "New"
          }
}

example 2 {
  "data": {
    "type": "string",
    "attributes":{
           "id": "001"
          }
}

如果你查看上面的python字典,只有属性对象下的值是不同的。那么,有什么方法可以为 { "data": { "type": "string", "attributes":{ } } } 定义父棉花糖方案,并将该父模式用于所有子模式。

标签: python-3.xjson-apipydantic

解决方案


我终于找到了答案,希望这会对某人有所帮助。

Pydantic 'create_model' 概念将通过将子模式作为字段值之一传递给 create_model 来帮助解决这种需求。

class Child(BaseModel):
   title: str
   name: str
 
class BaseParent(BaseModel):
    data: create_model('BaseParent', type=(str, ...), attributes=(Child, ...))

这将构建一个 BaseParent 模式结构,如下所示,

data=BaseParent(type='id', attributes=Child2(title='test002', name='Test'))

推荐阅读