Defining Multi-Column Indexes Using ORM Declarative Mapping
from sqlalchemy import create_engine, Column, Integer, String, Index from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('postgresql://username:password@localhost/mydatabase') Base = declarative_base() class Employee(Base): __tablename__ = 'employees' id = Column(Integer, primary_key=True) last_name = Column(String) first_name = Column(String) department_id = Column(Integer) __table_args__ = ( Index('idx_employees_last_first', 'last_name', 'first_name'), ) Base.metadata.create_all(engine)
Creating Indexes After Table Definition
from sqlalchemy import create_engine, MetaData, Table, Index engine = create_engine('postgresql://username:password@localhost/mydatabase') metadata = MetaData(bind=engine) # Reflect the existing table employees = Table('employees', metadata, autoload_with=engine) # Create the index index = Index('idx_employees_last_first', employees.c.last_name, employees.c.first_name) index.create(engine)