python - 复合索引 SQLModel

标签 python database indexing model sqlmodel

我正在试验 SQLModel ( https://sqlmodel.tiangolo.com/ ),我不得不在几个字段之间创建一个复合索引,但我无法使用 SQLModel 库来完成它。

Db Model

我发现的唯一解决方法是直接使用 sqlalchemy 索引,而不是 index=true(在为唯一字段创建索引时来自 SQLModel 文档 - )

class Jump(SQLModel, table=True):
"""
SQL Table abstraction: Jump
Contains data belonging to a connection between a questionnaire-version and another
questionnaire-version
"""

origin_name: str = Field(primary_key=True)
origin_version: int = Field()
destination_name: str = Field()

__table_args__ = (
    Index(
        "compound_index_origin_name_version_destination_name", "origin_name", "origin_version", "destination_name"
    ),
)

最佳答案

这不是“解决方法”。这正是应该如何完成的(截至目前)。 SQLModel 背后的想法大概是提供一个用于构建表模型的工具包,这对来自 SQLAlchemy 的人来说非常熟悉,同时还提供了来自 Pydantic 模型的大部分好东西。

在某些情况下,SQLModel 显然以不同的方式做事,并且在某些方面它试图简化现有接口(interface)。例如。在 Field 构造函数上提供 foreign_key 参数,这样您就不需要从 SQLAlchemy 导入和实例化 ForeignKey

但在这种情况下,我真的看不出尝试更改现有工具有什么意义。 SQLAlchemy 声明式 ORM 模型允许您通过 __table_args__ 设置复合索引和其他表参数类属性。 SQLModel 的元类继承了这个特性。那么为什么要重新发明轮子呢? 🙂

除非您知道如何进一步简化它。在那种情况下,我相信塞巴斯蒂安会对相应的 PR 感到非常高兴。或 issue tracker 中的建议.

关于python - 复合索引 SQLModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70958639/

相关文章:

python - 使用 Python 进行轨迹可视化

python - 如何在 sympy + IPython 中禁用 init_printing

第一个值为 0 时的 SQL Server 平均值

mysql - 如何决定哪些字段必须在数据库表中建立索引

c# - 在捕获索引时使用 LINQ 展平列表

python - 为什么在不继承对象的情况下在 Python 2.7 中定义类不会生成 __mro__ 方法?

python - 如何将条目的值放入 tkinter 中的变量中

java - hibernate 。 PSQL异常 : bad value for type int : admin

database - Akka Actor : Handling DB Failures Without Losing Data

python - 将索引转换为列 - pandas