2013-11-21 2 views

답변

2

개체 그래프를 걷고 SQLAlchemy: Modification of detached object에 설명 된대로 그래프의 각 개체에 대해 expunge(), make_transient() 및 id = None 단계를 수행하여이 작업을 수행 할 수 있습니다.

+0

'그래프 워킹'을 어떻게 구현 했습니까? 붙여 넣을 수있는 샘플 코드가 있습니까? 건배. (나는 자식 행이 많은 부모 행을 가지며, 각 행에는 더 많은 자식 행이 있고 테이블의 부모 행의 복제본을 만들고 자식 및 그랜드 자식의 모든 관련 행을 자동으로 복제하려고합니다. 테이블.) – Soferio

+0

방금 ​​전에이 토론을 발견했습니다. 수동으로 수행해야합니다. https://groups.google.com/forum/#!topic/sqlalchemy/wb2M_oYkQdY – Soferio

+1

예, 컨테이너를 반복하고 관계를 수동으로 따릅니다. –

0

여기 내 샘플 코드입니다. 상담원에게는 최대 하나의 캠페인 만 있습니다.

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 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 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 # attatch child to parent. agent_id is a foreign key 
     s.add(c) 
     s.commit()