使用动态密钥创建 Pydantic 模型架构

nav*_*ule 5 python pydantic fastapi

我正在尝试为以下 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]

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是 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]
Run Code Online (Sandbox Code Playgroud)

我解析 AuthorInfoCreate 如下:

y = AuthorBookDetails( numberOfBooks = 10, bestBookIds = [3,5])
print(y)
print(type(y))

x = AuthorInfoCreate.parse_obj({"RAM" : y})
print(x)
Run Code Online (Sandbox Code Playgroud)

我看到以下错误。

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)
Run Code Online (Sandbox Code Playgroud)

我想了解如何更改 AuthorInfoCreate 以便我提到 json 模式。

Inf*_*ion 5

实际上,您应该从类型注释中删除 Type。您需要一个类的实例,而不是实际的类。尝试以下解决方案:

from typing import List,Dict
from pydantic import BaseModel

class AuthorBookDetails(BaseModel):
    numberOfBooks: int
    bestBookIds: List[int]

class AuthorInfoCreate(BaseModel):
    __root__: Dict[str, AuthorBookDetails]

class ScreenCreate(BaseModel):
    description: str
    authorInfo: AuthorInfoCreate
Run Code Online (Sandbox Code Playgroud)