Python 带有外键的动态SQLAlchemy表名

Python 带有外键的动态SQLAlchemy表名,python,database,sqlalchemy,Python,Database,Sqlalchemy,在此基础上,我正在将SQLite数据库/数据库模式转换为SQLAlchemy 在这种情况下,将动态生成一系列表,其中包含正在分析的基因组的名称。每个表都有一个对父表(参考基因组)的外键引用。如何设置外键 class Genome(DynamicName, Base): """ Defines database schema for the reference genome. """ __abstract__ = True TranscriptId = Co

在此基础上,我正在将SQLite数据库/数据库模式转换为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
关联。在这种情况下,我认为动态构建整个类而不是特定的部分要容易得多:

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
您只需要注意以一致的方式命名表和类