您始终可以使用关联对象:
class Genes2Experiments2Organs(Base):
__tablename__ = 'genes2experiments2organs'
gene_id = Column(Integer, ForeignKey('genes.id'), primary_key=True)
experiment_id = Column(Integer, ForeignKey('experiments.id'), primary_key=True)
organ_id = Column(Integer, ForeignKey('organs.id'), primary_key=True)
# relationships
gene = relationship("Gene", backref="map")
experiment = relationship("Experiment", backref="map")
organ = relationship("Organ", backref="map")
class Gene(Base):
__tablename__ = 'genes'
id = Column(Integer, primary_key=True)
gene_name = Column(String)
class Experiment(Base):
__tablename__ = 'experiments'
id = Column(Integer, primary_key=True)
experimentAccession = Column(String)
class Organ(Base):
__tablename__ = 'organs'
id = Column(Integer, primary_key=True)
organName = Column(String)
###########################################
def add_data():
session = Session()
gene = "BRCA2"
gene_to_add = Gene(gene_name = gene)
#session.add(gene_to_add)
experiment = "experiment1"
experiment_to_add = Experiment(experimentAccession = experiment)
#session.add(experiment_to_add)
organ = "brain"
organ_to_add = Organ(organName = organ)
#session.add(organ_to_add)
#gene_to_add.experiment_rel.append(experiment_to_add)
assoc_obj_to_add = Genes2Experiments2Organs(
gene = gene_to_add,
experiment = experiment_to_add,
organ = organ_to_add,
)
session.add(assoc_obj_to_add)
session.commit()
session.close()
add_data()