【问题标题】:Pydantic list of models with the same namePydantic 同名模型列表
【发布时间】:2019-12-11 11:06:28
【问题描述】:

假设我想要一个用户模型,它还包含“朋友”字段,该字段必须是用户列表:

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

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

【问题讨论】:

    标签: python python-3.x pydantic


    【解决方案1】:

    是的,您需要使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-09
      • 2021-11-03
      • 2021-01-07
      • 2021-11-26
      • 1970-01-01
      • 2021-12-17
      • 2022-01-15
      • 2021-09-06
      相关资源
      最近更新 更多