gpt4 book ai didi

python - 使用 alembic autogenerate 时忽略模型

转载 作者:行者123 更新时间:2023-12-05 05:11:54 39 4
gpt4 key购买 nike

我正在尝试使用 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 定义元类并将其传递给 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

关于python - 使用 alembic autogenerate 时忽略模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54978681/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com