Python 如何编写Pydantic模型以接受字典字典

Python 如何编写Pydantic模型以接受字典字典,python,fastapi,pydantic,Python,Fastapi,Pydantic,下面的代码已修改 我想知道如何更改BarModel和FooBarModel,以便他们接受分配给m1的输入。我尝试过使用\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu from pydantic import BaseModel class BarModel(BaseModel): whatever: float foo: str cla

下面的代码已修改 我想知道如何更改
BarModel
FooBarModel
,以便他们接受分配给
m1
的输入。我尝试过使用
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

from pydantic import BaseModel

class BarModel(BaseModel):
    whatever: float
    foo: str

class FooBarModel(BaseModel):
    banana: str
    bar: BarModel

m = FooBarModel(banana='a', bar={'whatever': 12.3, 'foo':'hello'})
m1 = FooBarModel({
  'a':{'whatever': 12.3, 'foo':'hello'},
  'b':{'whatever': 12.4, 'foo':'bye'}
})

print(m.dict())   # returns a dictionary:
print(m1.dict())  # TypeError

最终的解决方案将部署在FastAPI上下文中。

如果您所要做的只是在另一个模型中拥有一个
BarModel
的字典,这就回答了您的问题:

从键入import Dict开始
从pydantic导入BaseModel
类别模型(基本模型):
不管怎样:浮动
foo:str
类FooBarModel(基本模型):
字典:Dict[str,BarModel]
m1=FooBarModel(字典)={
'a':{'whatever':12.3,'foo':'hello'},
'b':{'whatever':12.4,'foo':'bye'}
}
打印(m1.dict())

你已经找到了你的神奇组合,但你还没有意识到

来自pydantic import BaseModel的

从键入导入Dict
类别模型(基本模型):
不管怎样:浮动
foo:str
类FooBarModel(基本模型):
香蕉:str
bar:Dict[str,BarModel]
m1=FooBarModel(banana=“a”,bar={
'a':{'whatever':12.3,'foo':'hello'},
'b':{'whatever':12.4,'foo':'bye'}
})
断言m1.dict()={'banana':'a','bar':{'a':{'whatever':12.3,'foo':'hello'},'b':{'whatever':12.4,'foo':'bye'}
这运行时没有任何错误

请注意,我们还有香蕉,如果您想丢弃它,只需删除即可

如果您想使用纯类型和一些静态分析器,您的示例将对此进行评估

输入import Dict,Union的

m=FooBarModel(banana='a',bar={'whatever':12.3,'foo':'hello'})
m:Dict[str,Union[str,Dict[str,Union[float,str]]]
但实际上你想要的是这个

输入import Dict,Union的

m1=FooBarModel({
'a':{'whatever':12.3,'foo':'hello'},
'b':{'whatever':12.4,'foo':'bye'}
})
m1:Dict[str,Union[str,Dict[str,Dict[str,Union[float,str][]]]

已使用{uuuuu root}实现上述功能语法,但仍然无法将其应用于FastAPI。此错误看起来很相关,这对我来说很有效。我还意识到,使用root,可以在不使用关键字参数的情况下传递原始数据。在FastAPI中如何导出BarModel仍然存在问题,但我正在慢慢解开这些问题。再次感谢。