2015-08-27 17 views
1

我得到這個錯誤之前:ValueError異常:「......」需要有字段中的值「......」這麼多的一對多關係可以用來

try: 
    newthing1 = Thing1() 
    newthing1.thing1 = data['thing1'] 
    newthing1.save() 
except (SystemExit, KeyboardInterrupt): 
    raise 
except Exception, e: 
    clientnamedb_logger.error('Exception:', exc_info=True) 
clientnamedb_logger.debug('create account - thing1 record created, thing1 id:%s' % newthing1.id) 
# 
# create an instance of Thing2 and save the thing2 record 
# 
try: 
    newthing2 = Thing2() 
    newthing2.target_id = target_id 
    newthing2.thing2_id = user_id 
    #newthing2.thing1 = data['datasharing_thing1'] 
    newthing2.thing1 = [newthing1.id] 
    newthing2.save() 
except (SystemExit, KeyboardInterrupt): 
    raise 
except Exception, e: 
    clientnamedb_logger.error('Exception:', exc_info=True) 

現在,我知道這是因爲newthing2在嘗試保存多對多關係時還不存在。我已經嘗試在分配newthing1.id列表之前執行保存權限,但是給出了一個空字段約束(我可以關閉它,但是我認爲這會給我兩行數據庫中的數據,這是我不想要的) 。

如何在newthing2.thing1字段中使用newthing1.id的數據保存一行,這是ManyToMany?有沒有辦法做到這一點,而不是兩次保存?會創建一個重複的行嗎?

+0

請用您的模型更新帖子。沒有它,我們無法確定哪些字段是m2m,哪些字段是必需的。 –

回答

1

嘗試保存不提交,這樣你得到的ID在你提交之前,像這樣:

 newthing1.save(commit=False) 

之後,你可以使用id,但你將不得不再次保存的東西2被保存後:

 newthing2.thing1 = [newthing1.id] 
    newthing2.save() 
    newthing1.save() 
相關問題