【问题标题】:dynamic SQLAlchemy table names with foreign keys带有外键的动态 SQLAlchemy 表名
【发布时间】:2016-02-17 04:26:10
【问题描述】:

my previous post 的基础上,我正在努力将 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 键关联,这是一对多的关系:许多AlignmentIds 与一个TranscriptId 关联。

【问题讨论】:

    标签: python database sqlalchemy


    【解决方案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
    

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

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 1970-01-01
      • 2019-11-24
      • 2017-02-27
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      相关资源
      最近更新 更多