【发布时间】:2019-12-11 11:06:28
【问题描述】:
假设我想要一个用户模型,它还包含“朋友”字段,该字段必须是用户列表:
class User(BaseModel):
id: int
name: str
friends: List[User]
但这是不可能的。有没有办法实现这种行为?
【问题讨论】:
标签: python python-3.x pydantic
假设我想要一个用户模型,它还包含“朋友”字段,该字段必须是用户列表:
class User(BaseModel):
id: int
name: str
friends: List[User]
但这是不可能的。有没有办法实现这种行为?
【问题讨论】:
标签: python python-3.x pydantic
是的,您需要使用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)
【讨论】: