pydantic set属性/字段动态模型
根据 docs :
允许_ moution
是否允许 setAttr (默认:true)
是否允许 setAttr
我有一个类:
class MyModel(BaseModel):
field1:int
class Config:
allow_mutation = True
如果我尝试动态添加一个字段:
model1 = MyModel(field1=1)
model1.field2 = 2
并且我得到此错误:
File "pydantic/main.py", line 347, in pydantic.main.BaseModel.__setattr__
ValueError: "MyModel" object has no field "field2"
显然,使用 setAttr
方法将导致相同的错误。
setattr(model1, 'field2', 2)
输出:
File "pydantic/main.py", line 347, in pydantic.main.BaseModel.__setattr__
ValueError: "MyModel" object has no field "field2"
我在这里想念什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在类中使用config对象,并将
extra
属性设置为“允许”,或将其用作extra = extair = extair.allow
kwargs在从<<<<<<<< a href =“ https://pydantic-docs.helpmanual.io/usage/model_config/” rel =“ noreferrer”> docs :
You can use the Config object within the class and set the
extra
attribute to "allow" or use it asextra=Extra.allow
kwargs when declaring the modelExample from the docs :
使用
extair.Allow
放置一个示例,以回答问题。Putting an example using
extra.allow
that answers the question asked.为了记录,Pydantic V2已用“冷冻” 表明田地是人造的:
但是 faux-immutability ()不应与额外的属性处理( extra ),这是一个显示区别的小例子:
For the record, Pydantic V2 has replaced
allow_mutation
with "frozen" to indicate fields are faux-immutable:But faux-immutability (frozen) should not be confused with extra attribute handling (extra), here's a small example to show the difference: