Multiple columns index when using the declarative ORM extension of sqlalchemy

后端 未结 2 1893
小鲜肉
小鲜肉 2021-01-30 02:45

According to the documentation and the comments in the sqlalchemy.Column class, we should use the class sqlalchemy.schema.Index to specify an index tha

2条回答
  •  旧巷少年郎
    2021-01-30 03:20

    those are just Column objects, index=True flag works normally:

    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'd like a composite index, again Table is present here as usual you just don't have to declare it, everything works the same (make sure you're on recent 0.6 or 0.7 for the declarative A.a wrapper to be interpreted as a Column after the class declaration is complete):

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

    In 0.7 the Index can be in the Table arguments too, which with declarative is 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"), )
    

提交回复
热议问题