【发布时间】:2021-09-21 07:14:00
【问题描述】:
在下面的示例中,您如何以及在何处设置默认值?
author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT)
【问题讨论】:
标签: python django django-models foreign-keys
在下面的示例中,您如何以及在何处设置默认值?
author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT)
【问题讨论】:
标签: python django django-models foreign-keys
要使SET_DEFAULT 起作用,default 应在ForeignKey 声明中使用:
author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT, default=None, null=True)
在这种情况下,设置为default 的任何内容都将在删除相关对象时使用。
编辑:
正如@MojixCoder 和@Ersain 所指出的,在这个例子中你需要设置null=True 否则删除ForeignKey 的实例会导致IntegrityError 被提升。
【讨论】:
null=True Django docs 时才有可能。
None,则需要null=True。很好的收获,谢谢