Constraints and indexes¶
Use SQLAlchemy’s standard schema objects directly:
from sqlalchemy import CheckConstraint, ForeignKey, Index, String
from sqlalchemy.orm import Mapped, mapped_column
class Product(Base):
__tablename__ = "products"
__table_args__ = (
CheckConstraint("price > 0", name="price_positive"),
Index("ix_products_sku", "sku", unique=True),
)
id: Mapped[int] = mapped_column(primary_key=True)
owner_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
sku: Mapped[str] = mapped_column(String)
Schema-qualified foreign keys should include the schema in their target, for
example ForeignKey("public.users.id").