[英]SQLModel behaves differently from Pydantic BaseModel in exclude_unset
I have the following code snippet我有以下代码片段
class Model(BaseModel):
is_required: float
a_float: Optional[float] = None
k: Optional[int] = None
k = Model(
**{
"is_required": 0.1,
"a_float": 1.2,
}
)
print(k.dict()) #{'is_required': 0.1, 'a_float': 1.2, 'k': None}
print(k.dict(exclude_unset=True)) #{'is_required': 0.1, 'a_float': 1.2}
This is understandable.这是可以理解的。 But once I switch to SQLModel using the following code, the result changed for exclude_unset.
但是,一旦我使用以下代码切换到 SQLModel,exclude_unset 的结果就会发生变化。
class Model(SQLModel):
is_required: float
a_float: Optional[float] = None
k: Optional[int] = None
k = Model(
**{
"is_required": 0.1,
"a_float": 1.2,
}
)
print(k.dict()) #{'is_required': 0.1, 'a_float': 1.2, 'k': None}
print(k.dict(exclude_unset=True)) #{'is_required': 0.1, 'a_float': 1.2, 'k': None}
Why does this happen, and is there a way for me to get a dict
where unsets are not included in the export using dict()
?为什么会发生这种情况,有没有办法让我使用
dict
dict()
获得一个未包含在导出中的未设置的字典?
I looked into this a bit, and as of today (version 0.0.6), SQLModel.dict(exclude_unset=True)
simply does not work as intended , at least when instantiated using the normal constructor.我对此进行了一些研究,截至今天(0.0.6 版),
SQLModel.dict(exclude_unset=True)
根本无法按预期工作,至少在使用普通构造函数实例化时是这样。 There is an open GitHub issue about this, and a PR that addresses it .有一个关于这个的开放 GitHub 问题,以及一个解决它的 PR 。
My guess would be that FastAPI (which clearly is the "intended usecase" of SQLModel) uses some variant of the from_orm
method, because this code works:我的猜测是 FastAPI(这显然是 SQLModel 的“预期用例”)使用了
from_orm
方法的一些变体,因为这段代码有效:
from types import SimpleNamespace
from typing import Optional
from sqlmodel import SQLModel
class Model(SQLModel):
is_required: float
kasdf: Optional[int] = None
a_float: Optional[float] = None
k = Model.from_orm(SimpleNamespace(is_required=0.1, a_float=1.2))
print(k2.dict()) # {'is_required': 0.1, 'a_float': 1.2, 'k': None}
print(k2.dict(exclude_unset=True)) # {'is_required': 0.1, 'a_float': 1.2}
Here I'm using SimpleNamespace
, which is simply a way to create an object with the provided names as fields在这里,我使用
SimpleNamespace
,这只是一种使用提供的名称作为字段创建对象的方法
s = SimpleNamespace(foo=3, bar="value")
print(s.foo) # 3
print(s.bar) # 'value'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.