python-3.x - 如何将 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":{ } } } 定义父棉花糖方案,并将该父模式用于所有子模式。
解决方案
我终于找到了答案,希望这会对某人有所帮助。
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'))
推荐阅读
- oracle - 同一数据库中两个不同实例的性能问题
- node.js - Socket.io - io.in(room).emit() 不适用于加入回调的房间
- c++ - 有没有比这段代码更好的读取文件字符的方法?
- c++ - 使用pcap捕获双vlan流量
- r - 如何使用列的名称读取或为 tibble 中的单个单元格分配值?
- python - 如何使用 dnf 在 RHEL 8 UBI 容器上安装 Python 3.8.1?
- c# - 使用 C# 从 Cloud Storage 存储桶中拉出
- c - 使用 pthread 让一个线程完成其他线程发送的所有磁盘写入?
- html - 如何创建 facebook 喜欢使用 css 加载骨架?
- swiftui - SwiftUI:如何仅在 iOS 上有条件地呈现 ActionSheet?