删除可空字段就是删除相关对象

Deleting nullable field is deleting related objects

我有一个 Tournament 模型与相关 Standings:

class Tournament(models.Model):
    standings = models.ForeignKey('Standings', blank=True, null=True)

我刚刚做了以下事情:

standings = Standings.objects.get(pk=pk)
standings.delete()

并且它也删除了相关的锦标赛。这不应该发生,因为 standings 是一个可为空的字段。

为什么会发生这种情况,我该怎么做才能防止这种情况再次发生?

Django 1.8 默认为 CASCADE:

When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey.

要更改该行为,您应该添加 on_delete 参数(从 Django 2.x 开始是必需的),如下所示:

standings = models.ForeignKey(
    'Standings', blank=True, null=True, on_delete=models.SET_NULL)