【问题标题】:Ignoring a model when using alembic autogenerate使用 alembic 自动生成时忽略模型
【发布时间】:2019-03-04 07:45:20
【问题描述】:

我正在尝试使用 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 中的那一行,并在升级到更新版本的数据库时获得我想要的行为。

我有什么遗漏吗?

【问题讨论】:

    标签: python sqlalchemy alembic


    【解决方案1】:

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

    1. 定义一个将skip_autogenerate 添加到Table.info 的mixin。这是基于 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 来定义一个元类并将它传递给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 中提供:
    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
    

    【讨论】:

      猜你喜欢
      • 2012-06-26
      • 2015-09-20
      • 1970-01-01
      • 2016-05-22
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多