如何让 alembic 识别 Flask 中多个模型文件中的模型

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

所以在 Flask 中我有 models.py,其中包含我所有的模型定义。我想将其分成 models 目录下的多个模型文件。

我已经尝试添加一些模型文件,例如 models/user_model.pymodels/booking_model.py 等,但 alembic 似乎没有检测到这些文件中的模型。

在 Flask 的标准 alembic.ini 中,我有:

# 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

我需要在这里添加一些东西来让 alembic 识别模型吗?

您需要编辑您的 env.py:

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

要完成此答案,您可以直接将所有 'Bases' 放入列表中,如下所示:

from myapp.mymodel1 import Model1Base
from myapp.mymodel2 import Model2Base
target_metadata = [Model1Base.metadata, Model2Base.metadata]

Link 到文档:http://alembic.zzzcomputing.com/en/latest/autogenerate.html#autogenerating-multiple-metadata-collections