简体   繁体   中英

Define foreign key in existing table

How would I define a foreign key between the tables in the example below? They have an identically named column, but I currently am unable to make joins.

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Table, Column, Integer, String

engine = create_engine('my connection details', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()

my_table = Table('my_table', 
    Base.metadata, 
    autoload=True, 
    autoload_with=engine, 
    schema='my_schema')

other_table = Table('other_table', 
    Base.metadata, 
    autoload=True, 
    autoload_with=engine, 
    schema='other_schema')

class MyClass(Base):
    __table__ = my_table

class OtherClass(Base):
    __table__ = other_table

I believe the ForeignKey s should be automatically reflected by sqlalchemy . Maybe the fact that you have two different schema s is the reason why it does not work in your case.

Anyways, according to Overriding Reflected Columns , you should be able to do something like:

my_table = Table('my_table', Base.metadata, 
    Column("my_id", Integer, ForeignKey("[other_schema].other_table.my_id")),
    autoload=True, autoload_with=engine, schema='my_schema')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM