gpt4 book ai didi

django - 与用户模型(django.contrib.auth)的一对一关系,无需级联删除

转载 作者:行者123 更新时间:2023-12-02 05:57:26 26 4
gpt4 key购买 nike

当删除发挥作用时,我对 OneToOneField 如何工作有点困惑。我能找到的唯一准权威信息来自this thread on django-developers :

I don't know if you discovered this yet, but the delete is working in one direction, but not in the direction you're expecting it to. For instance, using the models you posted in another message:

class Place(models.Model): 
name = models.CharField(max_length = 100)
class Restaurant(models.Model):
place = models.OneToOneField(Place, primary_key=True)

If you create a Place and a Restaurant that is linked to it, deleting the Restaurant will not delete the Place (this is the problem you're reporting here), but deleting the Place will delete the Restaurant.

我有以下模型:

class Person(models.Model):
name = models.CharField(max_length=50)
# ... etc ...
user = models.OneToOneField(User, related_name="person", null=True, blank=True)

通过这种方式设置,我可以使用 user.personUser 实例轻松访问 person

但是,当我尝试删除管理中的 User 记录时,它自然会向后级联到我的 Person 模型,正如线程所讨论的那样,显示了一些内容的:

您确定要删除用户“JordanReiter2”吗?以下所有相关项目都将被删除:

  • 用户:JordanReiter
    • 人物:JordanReiter
      • 提交内容:标题1
      • 提交内容:标题2

不用说,我不想想要删除Person记录或其任何后代!

我想我理解这个逻辑:因为 Person 记录中的 OneToOne 字段中有一个值,删除 User 记录会在数据库的 user_id 列中创建错误引用。

通常,解决方案是切换 OneToOne 字段所在的位置。当然,这实际上是不可能的,因为 User 对象几乎是由 django.contrib.auth 设置的。

有什么方法可以防止删除级联,同时仍然可以通过用户直接访问人员?创建扩展 django.contrib 版本的 User 模型是唯一方法吗?

更新

我更改了模型名称,希望现在更清晰一些。基本上,有数千条人员记录。并非每个人都有登录名,但即使有,他们也只有一个登录名。

最佳答案

结果是ForeignKey and OneToOneField have an attribute on_delete您可以将其设置为 models.SET_NULL,如下所示:

class Person(models.Model):
name = models.CharField(max_length=50)
# ... etc ...
user = models.OneToOneField(User, on_delete=models.SET_NULL, related_name="person", null=True, blank=True)

这导致了我想要的行为:User 模型被删除,而不触及 Person 记录。我忽略了它,因为它没有明确列在 OneToOneField 下,它只是说

Additionally, OneToOneField accepts all of the extra arguments accepted by ForeignKey...

很容易错过。

关于django - 与用户模型(django.contrib.auth)的一对一关系,无需级联删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6963252/

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