繁体   English   中英

带外键的动态SQLAlchemy表名

[英]dynamic SQLAlchemy table names with foreign keys

我之前的文章的基础上 ,我正在将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与一个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

您只需要注意以一致的方式命名表和类。

暂无
暂无

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

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