使用 alembic autogenerate 时忽略模型

Ignoring a model when using alembic autogenerate

我正在尝试使用 alembic 为我的数据库自动生成修订。在这样做的同时,我想忽略一些模型(它们具有当前版本 MySQL 不支持的数据类型)。这是我尝试过的方法,它似乎工作正常,但我不确定这是最惯用的方法

里面alembic/env.py

def include_object(object, type_, name, reflected, compare_to):
    if type_ == 'table' and name == 'model_to_be_ignored':
        return False
    return True

然后在 run_migrations_onlinerun_migrations_offline 里面我给了 include_object=include_object 这似乎工作正常。

理想情况下,我想使用 skip_autogenerate=True,但不确定我是否可以定义它,以便稍后我可以简单地删除 models.py 中的那一行,并在升级时获得我想要的行为到更新版本的数据库。

有什么我遗漏的吗?

据我所知,skip_autogenerate 不会由 Alembic 或 SQLAlchemy 自动处理。但是您可以像这样将其添加到 Table.info

  1. 定义一个 mixin,将 skip_autogenerate 添加到 Table.info。这是基于 Flask-SQLAlchemy 的 BindMetaMixin
class ModelInfoMetaMixin(object):
    def __init__(cls, name, bases, d):
        skip_autogenerate = d.pop("__skip_autogenerate__", None)

        super(ModelInfoMetaMixin, cls).__init__(name, bases, d)

        if skip_autogenerate is not None and getattr(cls, "__table__", None) is not None:
            cls.__table__.info["skip_autogenerate"] = skip_autogenerate
  1. 使用此 mixin 定义一个元数据 class 并将其传递给 declarative_base()
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base

class DefaultMeta(ModelInfoMetaMixin, DeclarativeMeta):
    pass

Model = declarative_base(cls=BaseModel, metaclass=DefaultMeta)
  1. 然后你可以用这个标记定义你的模型:
class OneModel(Model):
    __skip_autogenerate__ = True
    uuid = Column(UUID(as_uuid=True), primary_key=True)
  1. 最后,skip_autogenerate 将在 Alembic 的 include_object:
  2. 中可用
def include_object(object, name, type_, reflected, compare_to):
    # skip objects marked with "skip_autogenerate"
    if object.info.get("skip_autogenerate", False):
        return False

    return True