簡體   English   中英

找不到不同架構上的SqlAlchemy ForeignKey

[英]SqlAlchemy ForeignKey on different schema not found

所以在 2 個不同的模式上有 2 個不同的模型。 一個與另一個有外鍵關系。 我運行BaseOne.metadata.create_all(engine)然后BaseTwo.metadata.create_all(engine)我得到BaseTwo.metadata.create_all(engine) sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column...

BaseOne = declarative_base(metadata=MetaData(schema="a"))
BaseTwo = declarative_base(metadata=MetaData(schema="b"))

class Parent(BaseOne):
    __tablename__ = "parent"
    parent_id = Column(Integer, primary_key=True)
    other_col = Column(String(20))
    children = relationship("Child", backref="parent")

class Child(BaseTwo):
    __tablename__ = "child"
    child_id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("a.parent.parent_id"), nullable=False)

# Where I'm creating them
BaseOne.metadata.create_all(engine)
BaseTwo.metadata.create_all(engine)

應該注意,我還嘗試通過__table_args__明確說明架構。 此外,我已連接到我的 postgres 實例並驗證了父表是否存在於目標列中。

看來問題是由於我使用了多個MetaData對象。 似乎他們無法見面。 簡化為單個聲明性基礎並使用__table_args__來聲明模式似乎有效。 如果有人知道如何聲明多個元數據對象並且仍然能夠使用.create_all隨時發布。

這可以通過使用 Alembic 來管理表創建來解決。 確保所有鹼基都包含在target_metadata列表中,例如:

# pylint: skip-file
import os
from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config
from sqlalchemy import pool

import unimatrix.ext.octet.orm
import gpo.infra.orm


# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = [
    unimatrix.ext.octet.orm.metadata,
    gpo.infra.orm.Relation.metadata
]


# Configure SQLAlchemy to use the DB_URI environment variable.
config.set_main_option("sqlalchemy.url", os.environ["DB_URI"])


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection, target_metadata=target_metadata
        )

        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

``

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM