4

I am using Flask-SQLAlchemy to define my models, and then using Flask-Migrate to auto-generate migration scripts for deployment onto a PostgreSQL database. I have defined a number of SQL Views on the database that I use in my application like below.

However, Flask-Migrate now generates a migration file for the view as it thinks it's a table. How do I correctly get Flask-Migrate / Alembic to ignore the view during autogenerate?

SQL View name: vw_SampleView with two columns: id and rowcount.

class ViewSampleView(db.Model):
    __tablename__ = 'vw_report_high_level_count'

    info = dict(is_view=True)

    id = db.Column(db.String(), primary_key=True)
    rowcount = db.Column(db.Integer(), nullable=False)

Which means I can now do queries like so:

ViewSampleView.query.all()

I tried following instructions on http://alembic.zzzcomputing.com/en/latest/cookbook.html and added the info = dict(is_view=True) portion to my model and the following bits to my env.py file, but don't know where to go from here.

def include_object(object, name, type_, reflected, compare_to):
    """
    Exclude views from Alembic's consideration.
    """

    return not object.info.get('is_view', False)

...

context.configure(url=url,include_object = include_object)
Andy G
  • 820
  • 1
  • 8
  • 11

1 Answers1

5

I think (though haven't tested) that you can mark your Table as a view with the __table_args__ attribute:

class ViewSampleView(db.Model):
    __tablename__ = 'vw_report_high_level_count'
    __table_args__ = {'info': dict(is_view=True)}

    id = db.Column(db.String(), primary_key=True)
    rowcount = db.Column(db.Integer(), nullable=False)
jackotonye
  • 3,537
  • 23
  • 31
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
  • 1
    Worked like a charm! Note also to self and other readers that context.configure is set in two places in env.py: run_migrations_offline() and run_migrations_online() – Andy G Feb 05 '17 at 16:16