5

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

4

3 回答 3

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
于 2020-08-03T11:21:26.073 回答
3

对于那些如何初始化 Pydantic 类的人,@SKhalymon 给出了答案,

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



kishan = AuthorBookDetails( numberOfBooks = 10, bestBookIds = [0, 2, 3, 7])

balram = AuthorBookDetails( numberOfBooks = 15, bestBookIds = [10, 12, 14])

ram = AuthorBookDetails( numberOfBooks = 6, bestBookIds = [3, 5])

aic = AuthorInfoCreate(__root__={"KISHAN": kishan, "BALRAM": balram, "RAM": ram})

sc = ScreenCreate( description = "Best Authors And Their Books", authorInfo = aic)

print(sc.json())

输出:

{"description": "Best Authors And Their Books", "authorInfo": {"__root__": {"KISHAN": {"numberOfBooks": 10, "bestBookIds": [0, 2, 3, 7]}, "BALRAM": {"numberOfBooks": 15, "bestBookIds": [10, 12, 14]}, "RAM": {"numberOfBooks": 6, "bestBookIds": [3, 5]}}}}
于 2020-08-03T16:04:32.707 回答
0

来自pydantic 问题 #2100

__root__仅在父级支持。

这就是为什么无法使用

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

在上述问题中提出了以下解决方法

from typing import Any, Dict, List

from pydantic import BaseModel as PydanticBaseModel
from pydantic.utils import ROOT_KEY


class BaseModel(PydanticBaseModel):
    def __init__(__pydantic_self__, **data: Any) -> None:
        if __pydantic_self__.__custom_root_type__ and data.keys() != {ROOT_KEY}:
            data = {ROOT_KEY: data}
        super().__init__(**data)

...
...

现在可以以AuthorInfoCreate通常的方式使用模型

aic = AuthorInfoCreate(**{"KISHAN": kishan, "BALRAM": balram, "RAM": ram})

PR #2237应该使上述解决方法变得不必要。

于 2021-02-11T13:25:32.033 回答