ValueError:“…”需要有字段“…”的值,然后才能使用此manytomy关系

2024-10-01 09:16:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了这个错误:

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)

现在,我知道这是因为在试图挽救多对多关系时,新思维还不存在。我尝试在分配newthing1.id的列表之前执行save权限,但是这给了一个空字段约束(我可以将其关闭,但我认为这会在数据库中给我两行,我不想要)。在

如何在newthing2.thing1字段中保存包含newthing1.id的数据的行,该字段是manytomy?有没有办法做到这一点而不存两次?这会产生一个重复的行吗?在


Tags: iddatasaveexceptionerrorloggerexcraise
1条回答
网友
1楼 · 发布于 2024-10-01 09:16:41

尝试在不提交的情况下保存,这样可以在提交之前获取ID,如下所示:

     newthing1.save(commit=False)

之后,您可以使用id,但在保存第2项后,您必须再次保存:

^{pr2}$

相关问题 更多 >