如何插入具有多对多关系的记录?

时间:2014-07-24 14:04:18

标签: python mysql sqlalchemy many-to-many

我在这个课程中有一个班级Consignments我与Sims班级有关系:

class Consignments(Base):
    __tablename__ = "consignments"
    id = Column(
        Integer,
        Sequence('consignments_id', optional=True),
        primary_key=True
    )
    consignment_agents_id = Column(Integer, ForeignKey(Agents.id))    
    consignment_agent = relationship(
        Agents,
        primaryjoin=Agents.id == consignment_agents_id,
        uselist=False,
        backref="consignments"
    )
    consignment_teamleader_id = Column(Integer, ForeignKey(Agents.id))
    consignment_teamlead = relationship(
        Agents,
        primaryjoin=Agents.id == consignment_teamleader_id,
        uselist=False,
        backref="team_consignments"
    )
    consignment_timestamp = Column(DateTime, index=True)
    created_by_agent_id = Column(Integer, ForeignKey(Agents.id))
    created_by_agent = relationship(
        Agents,
        primaryjoin=Agents.id == created_by_agent_id,
        uselist=False,
        backref="created_consignments"
    )
    transactions_id = Column(Integer, ForeignKey(Transactions.id))
    transaction = relationship(Transactions, backref="consignments", uselist=False)
    status = Column(Unicode(40), index=True)
    complete_stamp = Column(DateTime, index=True)

    sims = relationship(Sims, secondary=consignment_to_sim, backref="consignments")

注意:sims关系consignment_to_sim这是一个表格:

consignment_to_sim = Table(
    "consignment_to_sim",
    Base.metadata,
    Column("sims_iccid", Unicode(40), ForeignKey("sims.iccid"), primary_key=True, onupdate="cascade"),
    Column(
        "consignments_id",
        Integer,
        ForeignKey("consignments.id"),
        primary_key=True
    )
)

现在我想要添加一个像这样的货物:

@task
def do_consignment_task(store):
    s = sqlahelper.get_session()
    consign = store.gen_consignment()
    ca = Agents.by_id(store.consignment_agents_id)
    consign.consignment_agents_id = store.consignment_agents_id
    consign.consignment_teamleader_id = ca.ou[0].lead_agents_id
    consign.consignment_timestamp = func.now()
    consign.created_by_agent_id = store.consignment_agents_id
    consign.complete_stamp = func.now()
    consign.status = "SUCCESS"
    for sim in store.sims:
        consign.sims.append(sim)
    s.add(consign)
transaction.savepoint()

store.sims是SIM卡列表。

上面的代码给出了以下错误:

IntegrityError: (IntegrityError) (1062, "Duplicate entry '1302-37050' for key 'PRIMARY'", None) 

我已尝试过这个question的建议而没有运气。我也看过这个question

1 - 在我的实例中,我做错了什么? 2 - 如何插入多对多表格?
3 - 我可以使用sqlalchemy.sql.expression.insert插入多对多吗?

以防万一,这里是完整的traceback

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法, 我刚刚在for循环中添加了一个检查:

for sim in store.sims:
    if sim in consign.sims:
        continue
    else:
        consign.sims.append(sim)
s.add(consign)

虽然列表中没有重复的条目,但这似乎解决了它 我希望这可以帮助别人。