如何使用 pydantic 使用 uuid 创建 children

How to create children with uuid with pydantic

我尝试创建 children 的 Foo,每个都应该有自己的 uuid。在实际代码中,不会创建 Foo 实例,只会创建 children。 children 稍后会保存在数据库中,uuid 是从数据库中检索权限objects。

在第一个代码片段中,我尝试使用 init 方法,这导致了 AttributeError。我还尝试使用类方法,这会导致丢失 child objects.

中的所有字段

如果我在第二个片段中每个 child 获得相同的 uuid,这对我来说很有意义,因为它作为默认值传递。

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

有没有更好的方法为每个 child 创建一个 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

您可以使用 default_factory 参数:

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