多个表上外键关系的重复键错误

duplicate key error on relationship of foreign key on multiple tables

我正在尝试将数据插入 table,它的 ID 映射到另一个 table,我希望它能创建我的关系所需的数据...问题是在在Parent中,我还有另外一个关系,在Child中,我也从parent中与Child相关...见下:

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 table 两次,因为它在 parent 和 childa 中被引用,因为我不断得到 childb_id 的重复键。 .. 知道如何防止这种情况发生吗?

我创建工厂的方式是创建父对象并提交会话:

Parent()
Session.commit()

我怀疑您在两个子工厂中得到相同的 n 号码。你能试试这样吗?

class ParentTable(factory.alchemy.SQLAlchemyModelFactory)
    class Meta:
        ....

    parent_field = factory.Sequence(lambda n: 2*n + 1)
    childa = factory.SubFactory(ChildA)
    childb = factory.SubFactory(ChildB)

在后台,您对 ParentTable() 的调用将转换为:

  1. 致电ChildATable()
  2. ChildATable() 内,调用 ChildBTable()
  3. 再次调用 ChildBTable(),这次从 ParentTable()

如果您希望两个工厂使用相同的 ChildB() 对象,您可以按如下方式更改 ParentTable() 工厂:

class ParentTable(factory.alchemy.SQLAlchemyModelFactory)
    class Meta:
        ....

    parent_field = factory.Sequence(lambda n: n + 1)
    childa = factory.SubFactory(ChildA,
        # Forward our `childb` to the `ChildA()` factory
        childb=factory.SelfAttribute('..childb'),
    )
    childb = factory.SubFactory(ChildB)