Adding indexes to SQLAlchemy models after table creation

Given the model class from the original question.

class MyModel(db.Model):
    __tablename__ = 'targets'
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(2048))

You cannot just add index=True because even if you called db.Model.metadata.create_all() the index will not be created on an already created table.

Instead, you need to create an independent Index object, and then create it. It will look something like this:

class MyModel(db.Model):
    __tablename__ = 'targets'
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(2048))

mymodel_url_index = Index('mymodel_url_idx', MyModel.url)

if __name__ == '__main__':
    mymodel_url_index.create(bind=engine)

Now where engine comes from will be up to your sqlalchemy configuration, but this code should convey the gist of what needs to happen.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)