gpt4 book ai didi

python - Pydantic 设置属性与默认函数

转载 作者:行者123 更新时间:2023-12-05 01:08:40 70 4
gpt4 key购买 nike

是否可以为不可变 Pydantic Models 传递函数 setter ? .

例如:

from uuid import uuid4, UUID
from pydantic import BaseModel
from datetime import datetime

def generate_uuid():
return uuid4()

def get_datetimenow():
return datetime.now()

class Item(BaseModel):

class Config:
allow_mutation = False
extra = "forbid"

id: UUID
created_at: datetime

我想要方法 generate_uuidget_datetimenow 来设置属性。

>>> Item()
ValidationError: 2 validation errors for Item
id
field required (type=value_error.missing)
created_at
field required (type=value_error.missing)

虽然我想获得一个 Item 对象,并自动设置了 idcreated_at。与运行时相同的结果:

>>> Item(id=generate_uuid(), created_at=get_datetimenow())
Item(id=UUID('8f898730-3fad-4ca9-9667-c090f62a2954'), created_at=datetime.datetime(2021, 1, 19, 21, 13, 7, 58051))

最佳答案

您可以使用 default_factory Field 的参数与任意函数。像这样:

from uuid import uuid4, UUID
from pydantic import BaseModel, Field
from datetime import datetime

class Item(BaseModel):

class Config:
allow_mutation = False
extra = "forbid"

id: UUID = Field(default_factory=uuid4)
created_at: datetime = Field(default_factory=datetime.now)

关于python - Pydantic 设置属性与默认函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65798785/

70 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com