SQLModel example: Unique constraint over multiple columns
In the following example, we create a Unique constraint over multiple columns (seller
and url
) in SQLModel.
from sqlmodel import SQLModel, Field, UniqueConstraint
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__ = (
UniqueConstraint('seller', 'url', name='unique_seller_url'),
)
You can choose the name
parameter of UniqueConstraint
to your liking. It’s used to name the constraint in the database.