django - 保存模型并在保存后获取它以将其用作 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,并确保它已保存。
解决方案
模型的.save()
方法不返回任何内容,因此您的note
变量是None
,因此对象的创建ActionItem
会得到一个None
供note
参考,从而引发错误。
我们可以通过使用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))
推荐阅读
- visual-studio - VS 2019 更新后尝试构建 Xamarin.Android 时出错
- javascript - 如何使用时刻动态从周数中找到周开始日期
- javascript - Foreach 仅循环通过表格的最后一列(ES6)
- c - C中sendto()和recvfrom()之间的形式参数区别
- javascript - 如何防止 Bootstrap Modal 自动关闭?
- javascript - 使用数据表进行高级搜索
- python - 如何更改日期列表上的日期格式(并在通过 openpyxl 保存到 excel 时保留该日期格式)?
- java - 有没有一种方法可以在不手动遍历 AST 的情况下获取方法中的所有语句
- laravel - 如何在 Laravel Dusk 中覆盖环境变量
- php - PHP 5.6.40 Windows,FTPS 连接失败(SSL/TLS 握手失败)