首页 > 解决方案 > 保存模型并在保存后获取它以将其用作 ForeignKey 以创建另一个模型

问题描述

我有以下2个模型:

class Note(models.Model):
    name= models.CharField(max_length=35)

class ActionItem(models.Model):
    note = models.models.OneToOneField(Note, on_delete=models.CASCADE)
    target = models.CharField(max_length=35)
    category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)

在其他模型中(基于某些条件),我触发了一个创建注释的实用函数:

def create_note(target=None, action=None):

    note = Note(target=target, name=name).save()
    transaction.on_commit(
        ActionItem(note=note, target=target).save())

我收到以下错误:

null value in column "note_id" violates not-null constraint
DETAIL:  Failing row contains (6, null).

如果我使用:

因此,我认为出现错误是因为save, 不返回任何内容。我需要 Note 将其作为 FK 传递给 ActionItem,并确保它已保存。

标签: djangodjango-models

解决方案


模型的.save()方法不返回任何内容,因此您的note变量是None,因此对象的创建ActionItem会得到一个Nonenote参考,从而引发错误。

我们可以通过使用Note.objects.create(..)which.saves()并返回对象来解决它:

def create_note(target=None, action=None):
    note = Note.object.create(target=target, name=name)
    transaction.on_commit(lambda: ActionItem.object.create(note=note, target=target))

或者,我们可以先构造对象,然后再构造.save()它:

def create_note(target=None, action=None):
    note = Note(target=target, name=name)
    note.save()
    transaction.on_commit(lambda: ActionItem.object.create(note=note, target=target))

推荐阅读