如何将外键值插入SQLAlchemy中的表中

时间:2015-06-24 17:37:08

标签: python sql

我正在尝试将PrimaryTable的主键映射到SecondTable的外键。这些表在SQL中设置:

create table PrimaryTable
(
    id bigint IDENTITY(1,1) PRIMARY KEY, 
    name varchar(64) NOT NULL, 
    loader_class varchar(32) NOT NULL
)

create table SecondTable
(
    id bigint IDENTITY(1,1) PRIMARY KEY, 
    ABBRV char(3) NOT NULL, 
    foreign_key bigint NOT NULL FOREIGN KEY REFERENCES PrimaryTable(id),
)

我用来插入这些表并设置外键关系的代码,但我不认为foreign_key = ForeignKey("SecondTable.id")是正确的,但我不知道怎么办可能主键是外键:

Base = automap_base()
engine = OurData.Connectionengine()
Base.prepare(engine, reflect=True)

Base.metadata.create_all(engine, checkfirst=True)
Session = sessionmaker(bind=engine)
session = Session()

PrimaryTable = Base.classes.PrimaryTable
SecondTable = Base.classes.SecondTable

session.add_all([
     PrimaryTable(name = 'Apple',loader_class = 'AppleAdapter'),
     PrimaryTable(name = 'Google',loader_class =  'GoogleAdapter'),
     PrimaryTable(name = 'Bloomberg',loader_class =  'BloombergAdapter'),
     PrimaryTable(name = 'TR',loader_class =  'TRDataAdapter'),
     PrimaryTable(name = 'Microsoft',loader_class =  'MicrosoftBankAdapter')])

session.flush() #to get the primary key
session.commit()

session.add_all([
     SecondTable(ABBRV = 'APPL',foreign_key =  ForeignKey("SecondTable.id")),
     SecondTable(ABBRV = 'GOOGL',foreign_key = ForeignKey("SecondTable.id")),
     SecondTable(ABBRV = 'BL',foreign_key = ForeignKey("SecondTable.id")),
     SecondTable(ABBRV = 'TR',foreign_key = ForeignKey("SecondTable.id")),
     SecondTable(ABBRV = 'MSFT',foreign_key = ForeignKey("SecondTable.id")])

谢谢

0 个答案:

没有答案