0

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?

4

1 に答える 1

2

例:

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() 

ドキュメント:複数の Mixin からのテーブル/マッパー引数の結合

于 2012-07-12T13:12:51.547 に答える