0
自動查找外鍵關係
我試圖得到一個SQLAlchemy的ORM類自動:SQLAlchemy的 - 用於插入
無論是查找外鍵的id字段
OR
條目,其中字段尚未在外鍵表中,將該行添加到外鍵表 - 並在原表中使用自動生成的標識。
舉例說明:
類定義
class EquityDB_Base(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
__table_args__ = {'mysql_engine': 'InnoDB'}
__mapper_args__= {'always_refresh': True}
id = Column(Integer, primary_key=True)
def fk(tablename, nullable=False):
return Column("%s_id" % tablename, Integer,
ForeignKey("%s.id" % tablename),
nullable=nullable)
class Sector(EquityDB_Base, Base):
name = Column(String(40))
class Industry(EquityDB_Base, Base):
name = Column(String(40))
sector_id = fk('sector')
sector = relationship('Sector', backref='industries')
class Equity(EquityDB_Base, Base):
symbol = Column(String(10), primary_key=True)
name = Column(String(40))
industry_id = fk('industry')
industry = relationship('Industry', backref='industries')
使用類設置行業和部門
for i in industry_record[]:
industry = Industry(id=i.id,
name=i.name,
sector=Sector(name=i.sector_name))
session.merge(industry)
結果 不幸的是,當我運行日是 - 數據庫爲扇區表中的每個重複使用'sector_name'添加單獨的行 - 例如,如果10個行業使用'Technology'作爲其扇區名稱,則10個行業中的每個行業都會獲得10個唯一的sector_id。
我想要的東西 - 是一個部門的名稱提出每次已在數據庫中,爲它的自動解析到相應的sector_id
我清楚地剛學SQLAlchemy的,但似乎無法瞭解如何啓用此行爲。
任何幫助,將不勝感激!