SQLModel example: Custom index over a column
In the following example, we create a custom SQLModel index over a single column.
Option 1: Directly in the field
This is recommended for single-column indexes due to its simplicity.
Just add the index=True
parameter to the field:
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)
You can choose the name
parameter of UniqueConstraint
to your liking. It’s used to name the constraint in the database.
Option 2: Using __table_args__
This is recommended for multi-column indexes (also called composite indexes).
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'),
)