Search code examples
pythonflaskalembicflask-migrate

flask-migrate wants to drop my indeces


I've got a Flask app with the following models:

class User(db.Model, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    city_id = db.Column(db.Integer, db.ForeignKey('cities.id'))

class City(db.Model):
    __tablename__ = 'cities'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False)
    user_ids = db.relationship('User', backref='city', lazy='dynamic')

I've run a migration to specify my indices and foreign key constraints:

def upgrade():
    op.create_foreign_key('fk_user_city', "users", "cities", ["city_id"], ["id"])
    op.create_index('city_idx', 'users', ['city_id'])

However, any time I create another new migration Alembic seems to want to drop my indexes.

Is there a way to freeze Alembic's autogeneration at the current DB/Model schema?


Solution

  • Check this page. You will need to change env.py under migrations folder.

    EnvironmentContext.configure.include_object 
    

    or

    EnvironmentContext.configure.include_schemas
    

    should be what you are looking for.