Flask SqlAlchemy and Migrate Creating tables always but not detecting the updates

1k Views Asked by At

I'm making second revision of changing the table structure adding new tables and columns, but flask sqlalchemy on migrate is creating all the tables again.

INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
INFO  [alembic.autogenerate.compare] Detected added table 'old_table'
INFO  [alembic.autogenerate.compare] Detected added table 'new_table'

expected behavior was old table should not be added again.. init.py

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate


db = SQLAlchemy()
migrate = Migrate()

def creat_app():
   ...
   db.init_app(app)
   migrate.init_app(app, db)

models.py

from package_name import db

class MetaFields(db.Model):
    __abstract__ = True

    created = db.Column(db.DateTime)

class Model1(MetaFields):
    __tablename__ = "new_table"
    __table_args__ = {"schema": "schema_name"}
1

There are 1 best solutions below

0
On

Got the migration working on flask db migrate to generate proper alembic patch on model changes.

Added below code in alembic env.py script:

schema = 'example'

def include_object(object, name, type_, reflected, compare_to):
    if type_ == "table" and object.schema != schema:
        return False
    else:
        return True

And updated include_schemas and include_object in the configuration script:

context.configure(
            ...
            include_schemas=True,
            include_object=include_object,
            ...
        )