问题描述
在下面的示例中,您如何-以及在哪里--设置默认值?
author = models.ForeignKey('Author',on_delete=models.SET_DEFAULT)
解决方法
要使 SET_DEFAULT
起作用,应在 ForeignKey
声明中使用 default
:
author = models.ForeignKey('Author',on_delete=models.SET_DEFAULT,default=None,null=True)
在这种情况下,删除相关对象时将使用设置为 default
的任何内容。
编辑:
正如@MojixCoder 和@Ersain 所指出的,在这个例子中你需要设置 null=True
否则删除 ForeignKey 的实例将导致 IntegrityError
被引发。