2013-11-21 40 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()