Let's say I want to have a User model which also contains "friends" field which has to be a list of users:
class User(BaseModel):
id: int
name: str
friends: List[User]
but it's not possible. Is there a way to achieve this behavior?
Yes you need to use update_forward_refs
, see self-referencing models in the docs.
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)
outputs:
test.py:18 <module>
u: User(
id=123,
name='hello',
friends=[
User(
id=321,
name='goodbye',
friends=[],
),
],
) (User)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.