SQLAlchemy clone table row with relations

前端 未结 2 1828
不知归路
不知归路 2020-12-16 21:24

Following on from this question SQLAlchemy: Modification of detached object.

This makes a copy of the object fine, but it loses any many-to-many relationships the or

相关标签:
2条回答
  • 2020-12-16 22:08

    I got this to work by walking the object graph and doing the expunge(), make_transient() and id = None steps on each object in the graph as described in SQLAlchemy: Modification of detached object.

    0 讨论(0)
  • 2020-12-16 22:16

    Here is my sample code. The agent has at most one campaign.

    from sqlalchemy.orm.session import make_transient
    
    def clone_agent(id):
        s = app.db.session
        agent = s.query(Agent).get(id)
        c = None
    
        # You need to get child before expunge agent, otherwise the children will be empty
        if agent.campaigns:
            c = agent.campaigns[0]
            s.expunge(c)
            make_transient(c)
            c.id = None
    
        s.expunge(agent)
        agent.id = None
    
        # I have unique constraint on the following column.
        agent.name = agent.name + '_clone'
        agent.externalId = - agent.externalId # Find a number that is not in db.
    
        make_transient(agent)
        s.add(agent)
        s.commit() # Commit so the agent will save to database and get an id
    
        if c:
            assert agent.id
            c.agent_id = agent.id # Attach child to parent (agent_id is a foreign key)
            s.add(c)
            s.commit()
    
    0 讨论(0)
提交回复
热议问题