首页 > 解决方案 > 如何为 Django 的“on_delete=models.SET_DEFAULT”设置默认值

问题描述

在下面的示例中,您如何以及在何处设置默认值?

author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT)

标签: pythondjangodjango-modelsforeign-keys

解决方案


For SET_DEFAULTto work,default应该在ForeignKey声明中使用:

author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT, default=None, null=True)

default在这种情况下,删除相关对象时将使用设置为的任何内容。

编辑:正如@MojixCoder 和@Ersain 所指出的,在此示例中,您需要设置null=True否则删除 ForeignKey 的实例将导致IntegrityError引发。


推荐阅读