2016-02-16 45 views
0

基於my previous post構建,我正致力於將SQLite數據庫/數據庫模式轉換爲SQLAlchemy。帶外鍵的動態SQLAlchemy表名

在這裏,動態生成一系列表格,並分析基因組名稱。每個表都有一個對父表(參考基因組)的外鍵引用。我怎樣才能建立外鍵

class Genome(DynamicName, Base): 
    """ 
    Defines database schema for the reference genome. 
    """ 
    __abstract__ = True 
    TranscriptId = Column(String, primary_key=True) 
    AnalysisA = Column(Integer) 
    child = relationship('') # how to declare dynamic name? 


class AlignedGenome(DynamicName, Base): 
    """ 
    Defines database schema for a target (aligned) genome. 
    """ 
    __abstract__ = True 
    AlignmentId = Column(String, primary_key=True) 
    TranscriptId = Column(String, ForeignKey('')) # how to declare dynamic name? 
    AnalysisZ = Column(Integer) 
    parent = relationship('') # how to declare dynamic name? 


def build_genome_table(genome, is_ref=False): 
    d = {'__tablename__': genome} 
    if is_ref is True: 
     table = type(genome, (Genome,), d) 
    else: 
     table = type(genome, (AlignedGenome,), d) 
    return table 

父和子表都通過TranscriptId關鍵,這是一個一對多的關係關聯:許多AlignmentId s的一個TranscriptId相關。

回答

1

在這種情況下,我認爲這是更容易只是建立全班動態,而不是具體的件:

def build_genome_table(genome, is_ref=False): 
    if is_ref is True: 
     table = type(genome, (Base,), { 
      "__tablename__": genome, 
      "TranscriptId": Column(String, primary_key=True), 
      "AnalysisA": Column(Integer), 
      "child": relationship("Aligned" + genome), 
     }) 
    else: 
     table = type("Aligned" + genome, (Base,), { 
      "__tablename__": "Aligned" + genome, 
      "AlignmentId": Column(String, primary_key=True), 
      "TranscriptId": Column(String, ForeignKey(genome + ".TranscriptId")), 
      "AnalysisZ": Column(Integer), 
      "parent": relationship(genome), 
     }) 
    return table 

你只需要照顧的名字一致的方式表和類。