我正在尝试为以下 JSON 实现 Pydantic 模式模型。
{
"description": "Best Authors And Their Books",
"authorInfo":
{
"KISHAN":
{
"numberOfBooks": 10,
"bestBookIds": [0, 2, 3, 7]
},
"BALARAM":
{
"numberOfBooks": 15,
"bestBookIds": [10, 12, 14]
},
"RAM":
{
"numberOfBooks": 6,
"bestBookIds": [3,5]
}
}
}
这是 Pydantic 中的模式对象
from typing import List, Type, Dict
from pydantic import BaseModel
class AuthorBookDetails(BaseModel):
numberOfBooks: int
bestBookIds: List[int]
class AuthorInfoCreate(BaseModel):
__root__: Dict[str, Type[AuthorBookDetails]]
#pass
class ScreenCreate(BaseModel):
description: str
authorInfo: Type[AuthorInfoCreate]
我正在解析 AuthorInfoCreate 如下:
y = AuthorBookDetails( numberOfBooks = 10, bestBookIds = [3,5])
print(y)
print(type(y))
x = AuthorInfoCreate.parse_obj({"RAM" : y})
print(x)
我看到以下错误。
numberOfBooks=10 bestBookIds=[3, 5]
<class '__main__.AuthorBookDetails'>
Traceback (most recent call last):
File "test.py", line 44, in <module>
x = AuthorInfoCreate.parse_obj({"RAM": y})
File "C:\sources\rep-funds\env\lib\site-packages\pydantic\main.py", line 402, in parse_obj
return cls(**obj)
File "C:\sources\rep-funds\env\lib\site-packages\pydantic\main.py", line 283, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for AuthorInfoCreate
__root__ -> RAM
subclass of AuthorBookDetails expected (type=type_error.subclass; expected_class=AuthorBookDetails)
我想了解如何更改 AuthorInfoCreate 以便我提到 json 架构。