具有相同名称的模型的金字塔列表

问题描述 投票:0回答:1

比方说,我希望有一个User模型,其中也包含必须是用户列表的“ friends”字段:

class User(BaseModel):
    id: int
    name: str
    friends: List[User]

但是不可能。有没有办法实现这种行为?

python python-3.x pydantic
1个回答
0
投票

是,您需要使用update_forward_refs,请参阅文档中的self-referencing models

from typing import List

from devtools import debug

from pydantic import BaseModel


class User(BaseModel):
    id: int
    name: str
    friends: List['User']


User.update_forward_refs()

u = User(id=123, name='hello', friends=[dict(id=321, name='goodbye', friends=[])])

debug(u)

输出:

test.py:18 <module>
    u: User(
        id=123,
        name='hello',
        friends=[
            User(
                id=321,
                name='goodbye',
                friends=[],
            ),
        ],
    ) (User)
© www.soinside.com 2019 - 2024. All rights reserved.