gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:16:37 30 4
gpt4 key购买 nike

我有一个带有相关StandingsTournament模型:

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

我刚刚做了以下事情:

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

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

为什么会发生这种情况?我可以采取什么措施来防止这种情况再次发生?

最佳答案

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)

关于python - 删除可为空字段就是删除相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54289528/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com