SQLModel 示例:在列上创建自定义索引
在以下示例中,我们在单个列上创建自定义 SQLModel 索引。
选项 1:直接在字段中
由于简单,这推荐用于单列索引。
只需向字段添加 index=True 参数:
sqlmodel_custom_index.py
from sqlmodel import SQLModel, Field
class Offer(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
seller: str = Field(description="Name of the seller", index=True)你可以随意选择 UniqueConstraint 的 name 参数。它用于在数据库中命名约束。
选项 2:使用 __table_args__
这推荐用于多列索引(也称为复合索引)。
sqlmodel_custom_index.py
from sqlmodel import Index, SQLModel, Field
class Offer(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
seller: str = Field(description="Name of the seller")
url: str = Field(description="URL to the product page for this seller")
__table_args__ = (
Index('idx_seller', 'seller', 'url'),
)If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow