Multiple column index when using declarative sqlalchemy ORM extension

As per documentation: http://docs.sqlalchemy.org/en/latest/core/constraints.html#indexes

and the comments in the sqlalchemy.Column class, we must use the sqlalchemy.schema.Index class to specify an index that contains several multiple indexes.

However, the example shows how to do this directly using the Table object as follows:

 meta = MetaData() mytable = Table('mytable', meta, # an indexed column, with index "ix_mytable_col1" Column('col1', Integer, index=True), # a uniquely indexed column with index "ix_mytable_col2" Column('col2', Integer, index=True, unique=True), Column('col3', Integer), Column('col4', Integer), Column('col5', Integer), Column('col6', Integer), ) # place an index on col3, col4 Index('idx_col34', mytable.c.col3, mytable.c.col4) 

How to do this if we use a declarative ORM extension?

 class A(Base): __tablename__ = 'table_A' id = Column(Integer, , primary_key=True) a = Column(String(32)) b = Column(String(32)) 

I need an index in columns "a" and "b".

+52
python database indexing orm sqlalchemy
Jul 08 2018-11-11T00:
source share
1 answer

these are just Column objects, the index = True flag works fine:

 class A(Base): __tablename__ = 'table_A' id = Column(Integer, primary_key=True) a = Column(String(32), index=True) b = Column(String(32), index=True) 

if you need a composite index, Table is here again, as usual, you just don’t need to declare it, everything works the same way (make sure you use the last 0.6 or 0.7 for declarative Aa wrapper, which will be interpreted as Column after declaration class):

 class A(Base): __tablename__ = 'table_A' id = Column(Integer, primary_key=True) a = Column(String(32)) b = Column(String(32)) Index('my_index', Aa, Ab) 

In 0.7, the Index can also be in the arguments of Table , which with the declaration via __table_args__ :

 class A(Base): __tablename__ = 'table_A' id = Column(Integer, primary_key=True) a = Column(String(32)) b = Column(String(32)) __table_args__ = (Index('my_index', "a", "b"), ) 
+82
Jul 08 '11 at 16:00
source share
β€” -



All Articles