Search code examples
pythonflaskalembic

How to get alembic to recognise models from multiple model files in Flask


So in Flask I have models.py which contains all of my model definitions. I'd like to separate this out into multiple model files under a models directory.

I've given this a try by adding some model files such as models/user_model.py, models/booking_model.py etc. but alembic doesn't seem to detect the models in these files.

In the standard alembic.ini with Flask I have:

# A generic, single database configuration.

[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

Do I need to add something here to get alembic to recognise the models?


Solution

  • You need to edit your env.py:

    # add your model's MetaData object here
    # for 'autogenerate' support
    from your_cool_app.models import *
    target_metadata = db.Model.metadata