如何在来自SQLAlchemy中两个不同数据库的两个不同表中使用外键?

时间:2019-05-30 05:43:23

标签: python sqlalchemy graphql

我有两个表(ORDER和SECURITY),一个表来自PostgreSQL,另一个来自SQLServer。我想在ORDER表中使用外键。我该怎么办?

database.py

engine1 = create_engine('postgres://postgres:pwd@**.**.**.***:####/testdb')
engine2 = create_engine('mssql+pymssql://user:pwd@**.**.**.***/GraphQL_Test')

meta_data1 = MetaData(bind=engine1)
meta_data2 = MetaData(bind=engine2)

db_session1 = ...
db_session2 = ...

Base1 = declarative_base(metadata=meta_data1, bind=engine1)
Base1.query = db_session1.query_property()

Base2 = declarative_base(metadata=meta_data2, bind=engine2)
Base2.query = db_session2.query_property()

def init_db():

    Base1.metadata.drop_all(bind=engine1)
    Base1.metadata.create_all(bind=engine1)

    # Create the fixtures
    ibm = Order(name='b100kibm',securitytype='Equity',security='ibm',status='new', securityid2 = 20)
    db_session1.add(ibm)
    msft = Order(name='b500kmsft',securitytype='Equity',security='msft',status='complete', securityid2 = 10)
    db_session1.add(msft)
    db_session1.commit()

models.py

from database import Base1
from database import Base2    

class Security(Base2):
    __tablename__ = "security"
    __table_args__ = {'schema' : 'sec'}

    id = Column(BigInteger, primary_key = True)
    name = Column(String(200))
    securitytypeid = Column(Integer)


class Order(Base1):
    __tablename__ = 'order'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    securitytype = Column(String)
    security = Column(String)
    status = Column(String)
    securityid2 = Column(Integer, ForeignKey(Security.id), nullable=False)

我收到错误:

(psycopg2.errors.InvalidSchemaName) schema "sec" does not exist
[SQL:
CREATE TABLE "order" (
        id SERIAL NOT NULL,
        name VARCHAR,
        securitytype VARCHAR,
        security VARCHAR,
        status VARCHAR,
        securityid2 INTEGER NOT NULL,
        PRIMARY KEY (id),
        FOREIGN KEY(securityid2) REFERENCES sec.security (id)
)

]
(Background on this error at: http://sqlalche.me/e/f405)

如何在不同数据库的表中使用外键?

0 个答案:

没有答案