简体   繁体   English

在现有表中定义外键

[英]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 . 我相信ForeignKey应当由sqlalchemy自动反映。 Maybe the fact that you have two different schema s is the reason why it does not work in your case. 您可能拥有两个不同的schema这可能是它在您的情况下不起作用的原因。

Anyways, according to Overriding Reflected Columns , you should be able to do something like: 无论如何,根据Overriding Reflected Columns ,您应该能够执行以下操作:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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