Search code examples
pythonpython-3.xsqlalchemyalembic

Alembic autogenerate recerates existing indexes


I am using a simple mixin for all my tables:

class IdMixIn:
    id = sa.Column(sa.Integer, primary_key=True, index=True)

Example table:

class MyTable(Base, IdMixIn):
    __tablename__ = 'my_table'

    my_col: str = sa.Column(sa.String)

I have about thirty of these tables, and if I run alembic revision --autogenerate I will then have thirty rows, one for each table of an index creation:

op.create_index(op.f('ix_my_table_id'), 'my_table', ['id'], unique=False)

However, in postgres, each of these already have an index, named something like my_table_pkey. How do I let alembic know these already exist for all the tables?


Solution

  • There is no need to create index on primary key column, so you can only write

    class IdMixIn:
        id = sa.Column(sa.Integer, primary_key=True)
    

    Postgresql will automatically create index for this column