python sqlmodel-从数据库检索时,自动插入的可选ID值会导致类型错误
如果我有这样的模型:
class MyModel(DBModel, table=True):
id: Optional[int] = Field( primary_key=True)
那么,当将新记录保存到数据库时,ID会自动分配,这很棒。
但是,当我检索这样的模型时,我会得到类型错误,
model = session.get(MyModel, 1)
id: int = model.id # ID may be None error
是否有一种方法可以自动分配我的ID,但是在检索保存记录时也定义了ID类型?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确保在定义ID的字段时,您会明确陈述这样的ID的默认值
,因为我们没有设置ID,它采用了我们在
中设置的
。none
的python的默认值字段(默认值= none)当我们提交
数据库
时,设置ID。有关更多信息,请阅读文档 https://sqlmodel.tiangolo.com/tutororial/自动ID-NONE-REFRESH/
Make sure when defining a field for id, you explicitly state the default value for ID like this
Because we don't set the id, it takes the Python's default value of
None
that we set inField(default=None)
.IDs are set when we commit to the
database
.for more info read docs https://sqlmodel.tiangolo.com/tutorial/automatic-id-none-refresh/
您可能会在这里找到答案:
基本上您能做的就是这样定义您的模型:
就像您在说
myModelRead
必须具有属性ID
。请注意,只有mymodelbase
是sqlmodel
。其他类是pydantic
对象。You might find your answer here: https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/#multiple-models-with-inheritance
Basically what you can do is define your models like this:
Like that you are saying
MyModelRead
must have an attributeid
. Note that onlyMyModelBase
is aSQLModel
. The other classes arePydantic
objects.