python sqlmodel-从数据库检索时,自动插入的可选ID值会导致类型错误

发布于 2025-02-09 15:39:27 字数 340 浏览 2 评论 0 原文

如果我有这样的模型:

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类型?

If I have a model like this:

class MyModel(DBModel, table=True):

    id: Optional[int] = Field( primary_key=True)

Then when saving new records to the database, the ID is automatically assigned, which is great.

However, when I retrieve the model like this I get type errors

model = session.get(MyModel, 1)
id: int = model.id  # ID may be None error

Is there a way to auto-assign my IDs but also have the ID type defined when retrieving saved records?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

脸赞 2025-02-16 15:39:27

确保在定义ID的字段时,您会明确陈述这样的ID的默认值

class MyModel(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)

,因为我们没有设置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

class MyModel(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)

Because we don't set the id, it takes the Python's default value of None that we set in Field(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/

番薯 2025-02-16 15:39:27

您可能会在这里找到答案:

基本上您能做的就是这样定义您的模型:

class MyModelBase(SQLModel):
    arg1: str
    ...


class MyModel(MyModelBase, table=True):
    id: Optional[int] = Field( primary_key=True)


class MyModelRead(MyModelBase):
    id: int

就像您在说 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:

class MyModelBase(SQLModel):
    arg1: str
    ...


class MyModel(MyModelBase, table=True):
    id: Optional[int] = Field( primary_key=True)


class MyModelRead(MyModelBase):
    id: int

Like that you are saying MyModelRead must have an attribute id. Note that only MyModelBase is a SQLModel. The other classes are Pydantic objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文