你如何设置 Django 的默认值 'on_delete=models.SET_DEFAULT'
How do you set the default value for Django's 'on_delete=models.SET_DEFAULT'
在下面的示例中,如何以及在何处设置默认值?
author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT)
对于SET_DEFAULT
to work, default
应该在ForeignKey
声明中使用:
author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT, default=None, null=True)
在这种情况下,删除相关对象时将使用设置为default
的内容。
编辑:
正如@MojixCoder 和@Ersain 所指出的,在此示例中,您需要设置 null=True
否则删除 ForeignKey 的实例将导致引发 IntegrityError
。
在下面的示例中,如何以及在何处设置默认值?
author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT)
对于SET_DEFAULT
to work, default
应该在ForeignKey
声明中使用:
author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT, default=None, null=True)
在这种情况下,删除相关对象时将使用设置为default
的内容。
编辑:
正如@MojixCoder 和@Ersain 所指出的,在此示例中,您需要设置 null=True
否则删除 ForeignKey 的实例将导致引发 IntegrityError
。