gpt4 book ai didi

python - 带有外键的动态 SQLAlchemy 表名

转载 作者:太空宇宙 更新时间:2023-11-03 16:55:37 24 4
gpt4 key购买 nike

构建于 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 键关联,这是一种一对多关系:许多 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

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

关于python - 带有外键的动态 SQLAlchemy 表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35441590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com