我正在尝试将数据插入到具有映射到另一个表的 ID 的表中,并且我希望它创建我的关系所需的数据......问题是在父级中,我有另一个关系,而在子级中,我也与父母的孩子有关……见下文:
class Parent(Base):
parent_field = Column(Integer)
childa_id = Column(Integer, ForeignKey(ChildATable.childa_id))
childb_id = Column(Integer, ForeignKey(ChildBTable.childb_id))
childa = relationship(ChildATable)
childb = relationship(ChildBTable)
class ChildA(Base):
childa_id = Column(Integer, primary_key=True)
childb_id = Column(Integer, ForeignKey(ChildB.childb_id))
class ChildB(Base):
childb_id = Column(Integer, primary_key=True)
class ParentTable(factory.alchemy.SQLAlchemyModelFactory)
class Meta:
....
parent_field = factory.Sequence(lambda n: n + 1)
childa = factory.SubFactory(ChildA)
childb = factory.SubFactory(ChildB)
class ChildATable(factory.alchemy.SQLAlchemyModelFactory)
class Meta:
....
childa_id = factory.Sequence(lambda n: n + 1)
childb = factory.SubFactory(ChildB)
class ChildBTable(factory.alchemy.SQLAlchemyModelFactory)
class Meta:
....
childb_id = 1 #I need this to be hardcoded to 1
问题是,当我使用工厂插入 Parent 时,显然它尝试插入 childb 表两次,因为它在 parent 和 childa 中被引用,因为我不断获得 childb_id 的重复键......知道如何防止这种情况发生吗?
我创建工厂的方式是创建一个 Parent 对象并提交会话:
Parent()
Session.commit()