我收到此错误:
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字段(即ManyToMany)上保存包含newthing1.id数据的行?有没有办法这样做而不保存两次?这会创建一个重复的行吗?