python - 多个模型上的 Alembic 迁移

标签 python sqlalchemy alembic

我正在尝试使用 Alembic 为两个模型创建一个 --autogenerate 的修订版,但收到重复的表键错误。是否需要指定模式?如果可以,如何设置?我读过的文档说使用 __table_args__ = {'schema': 'somename'} ,但这没有帮助。非常感谢任何提示或建议。

我目前的设置是:

base.py

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

工作空间.py
from sqlalchemy import Column, Integer, String
from base import Base

class WorkspaceModel(Base):

    __tablename__ = 'workspaces'

    id = Column(Integer, primary_key=True)
    name = Column(String)

主机.py
from sqlalchemy import Column, Integer, String
from base import Base

class HostModel(Base):

    __tablename__ = 'hosts'

    id = Column(Integer, primary_key=true)
    ip = Column(String)

alembic/env.py
from host import HostModel
from workspace import WorkspaceModel
target_metadata = [HostModel.metadata, WorkspaceModel.metadata]

错误
ValueError: Duplicate table keys across multiple MetaData objects: "hosts", "workspaces"

最佳答案

为了从 @esdotzed@univerio 说清楚,你必须使用单个 Base.metadata - 但 仍然是 import 个别模型
在最初的问题中,alembic/env.py 应该是这样的:

from base import Base

# This two won't be referenced, but *have* to be imported to populate `Base.metadata`
from host import HostModel
from workspace import WorkspaceModel

target_metadata = Base.metadata
如果您没有 import 两个模型,自动生成的迁移最终会删除您的整个数据库 - 因为 Base.metadata 本身不知道任何模型。

关于python - 多个模型上的 Alembic 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053955/

相关文章:

python - alembic create_table 使用 declarative_base 派生对象

python - 使用 Keras : All layer names should be unique for discriminator 在 GPU 上训练 GAN

Python请求填写下拉菜单的表单

python - 为 solve_ivp 传递参数(新的 SciPy ODE API)

python - 使用 Flask Python 将点几何插入 PostGIS

python - SQLAlchemy:coalesce() 首先返回非 NULL 和非空结果

python - 获取 socket.gaierror : [Errno 8] nodename nor servname provided, 或未知

python - Flask-sqlalchemy 连接到现有数据库

python - Flask-SQLAlchemy 小写索引 - 跳过功能,SQLAlchemy 反射不支持

python - alembic 修订 - 多头(由于分支)错误