【问题标题】:How to create children with uuid with pydantic如何使用 pydantic 创建具有 uuid 的子级
【发布时间】:2020-12-27 22:13:14
【问题描述】:

我尝试创建 Foo 的孩子,每个孩子都应该有自己的 uuid。在实际代码中,不会创建 Foo 的实例,只有它的子级。子节点稍后将保存在数据库中,uuid 用于从数据库中检索正确的对象。

在第一个代码 sn-p 中,我尝试使用 init 方法,这会导致 AttributeError。我还尝试使用类方法,这会导致我的子对象中的所有字段丢失。

如果我第二个 sn-p 每个孩子都获得相同的 uuid,这对我来说很有意义,因为它是作为默认值传递的。

我可以将 uuid 创建放入孩子中,尽管在使用继承时感觉不对。

有没有更好的方法为每个孩子创建一个 uuid?

# foo_init_.py
class Foo(BaseModel):
    def __init__(self):
          self.id_ = uuid4()
# >>> AttributeError: __fields_set__

# foo_classmethod.py
class Foo(BaseModel):
    @classmethod
    def __init__(cls):
          cls.id_ = uuid4()
# >>> Bar loses id_ fields

from uuid import uuid4, UUID
from pydantic import BaseModel


class Foo(BaseModel):
    id_: UUID = uuid4()


class Bar(Foo):
    pass


class Spam(Foo):
    pass


if __name__ == '__main__':
    b1 = Bar()
    print(b1.id_)  # >>> 73860f46-5606-4912-95d3-4abaa6e1fd2c
    b2 = Bar()
    print(b2.id_)  # >>> 73860f46-5606-4912-95d3-4abaa6e1fd2c
    s1 = Spam()
    print(s1.id_)  # >>> 73860f46-5606-4912-95d3-4abaa6e1fd2c

【问题讨论】:

    标签: python fastapi pydantic


    【解决方案1】:

    你可以使用default_factory参数:

    class Foo(BaseModel):
        id_: UUID = Field(default_factory=uuid4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-07
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-11
      相关资源
      最近更新 更多