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'),
    )

同じカテゴリの類似記事をチェック: Sqlmodel Python Database