Joseph Turian
Joseph Turian

Reputation: 16580

SQLAlchemy add index in mixin based upon inherited table keys?

In SQLAlchemy, I want to define a mixin that automatically creates an Index in inheriting tables.

Assuming that the inheriting table has a member list called 'keys', I want the mixin to create in the inheriting table a single multi-column Index over the columns listed in keys. However, the mixin doesn't know what the keys are until the table is created!

How would I do this?

Upvotes: 1

Views: 597

Answers (1)

estin
estin

Reputation: 3121

Example:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import MetaData, Column, Index, Integer

metadata = MetaData()
Base = declarative_base(metadata=metadata)


class MyMixin(object):

    @declared_attr
    def __table_args__(cls):
        return (Index('test_idx_%s' % cls.__tablename__, *cls.INDEX),)


class MyModel(MyMixin, Base):
    __tablename__ = 'atable'
    INDEX = ('a', 'b',)
    id = Column(Integer, primary_key=True)
    a = Column(Integer)
    b = Column(Integer)
    c = Column(Integer)


if __name__ == '__main__':
    from sqlalchemy import create_engine
    engine = create_engine('sqlite:///', echo=True)
    metadata.bind = engine
    metadata.create_all() 

Docs: Combining Table/Mapper Arguments from Multiple Mixins

Upvotes: 3

Related Questions