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

时间:2016-02-22 12:17:56

标签: python sqlalchemy factory-boy

我正在尝试将数据插入到具有映射到另一个表的ID的表中,并且我希望它创建我的关系所需的数据...问题是在Parent中,我有另一种关系,并且孩子,我也与父母的孩子有关...见下文:

$ sed -e 's/^\([^ ]*\)[ ]\(.*$\)/\1:\2/' <file
2016/02/11:12:54:28 0071754407 7599 4727 2690
2016/02/11:14:07:41 0071754407 7599 4726 2690

问题是,当我使用工厂插入Parent时,显然它会尝试插入childb表两次,因为它在parent和childa中被引用,因为我一直在获取childb_id的重复键...我知道如何防止这种情况发生?

我创建工厂的方法是创建一个Parent对象并提交会话:

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

2 个答案:

答案 0 :(得分:1)

在幕后,您对ParentTable()的通话将转换为:

  1. 致电ChildATable()
  2. ChildATable()内,请致电ChildBTable()
  3. 再次致电ChildBTable(),这次是ParentTable()
  4. 如果您希望两家工厂使用相同的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)
    

答案 1 :(得分:0)

我怀疑你在这两个子事件中获得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)