I have a flask-sqlalchemy model:
class MyModel(db.Model): __tablename__ = 'targets' id = db.Column(db.Integer, primary_key=True) url = db.Column(db.String(2048))
The table has already been created, and is in use. I want to create an index on the url attribute, so I pass index=True to it:
url = db.Column(db.String(2048), index=True)
How can I make this index take effect, without deleting and recreating the table?
SQLAlchemy Index is used for assigning the identifiers for each of the particular row getting stored inside a table. We can have indexing based on the single column or collection of two or more columns together acting as an index to the table rows.
It is used when reflecting and creating databases in Python (using SQLAlchemy package). MetaData is a container object that keeps together many different features of a database (or multiple databases) being described.
create_all() creates foreign key constraints between tables usually inline with the table definition itself, and for this reason it also generates the tables in order of their dependency.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With