gpt4 book ai didi

python - 为什么django不删除一对一关系?

转载 作者:行者123 更新时间:2023-11-30 22:51:36 27 4
gpt4 key购买 nike

我有以下简单的关系:

class User(models.Model):
fields here

class UserProfile(models.Model):
user = models.OneToOneField(User)

我在 shell 中执行了以下操作:

user = User.objects.create(...)
profile = UserProfile.objects.create(user=user)
user.userprofile
...<UserProfile: UserProfile object>
user.userprofile.delete()
...(1, {'accounts.UserProfile': 1})
user.userprofile
...<UserProfile: UserProfile object>

从上面,你可以看到我创建了 User 和 UserProfile 实例。比我尝试删除 UserProfile 实例并且它被删除(至少看起来是这样)。比我做的 user.userprofile 就好像它从未被删除。

在深入研究 Django 删除方法后,我意识到当我执行 user.userprofile.delete() 时,Django 只是删除用户配置文件的 pk,其余字段不会被触及。我不明白的是我应该做什么才能得到以下结果:

user.userprofile.delete()
user.userprofile
...RelatedObjectDoesNotExist: User has no userprofile.

有人有一些想法或代码片段吗?

最佳答案

您可以从数据库重新加载用户:

user = User.objects.get(pk=user.pk)

这将刷新其所有属性,包括用户配置文件。

关于python - 为什么django不删除一对一关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38957082/

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