在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
相关联。
答案 0 :(得分: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
您只需要注意以一致的方式命名表和类。