更新或删除表“ users_user”违反外国钥匙约束“ articles_article_users_user_id”

发布于 2025-02-02 18:06:46 字数 370 浏览 1 评论 0原文

我正在使用Django V4。或反之亦然,所以我在文章模型中引用了用户on_delete = delete.do_nothing,但是当我尝试删除用户时,我会遇到此错误我以为是吗?我如何通过这件事并实现我倾向于做的事情而不会限制错误?谢谢

class Article(models.Model):
     title = models.CharField(max_length=355)
     author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, 
     related_name='articles')
     .....

I am working with Django v4.* and I have linked 2 table/model Users and Articles and my aim is when user is deleted I don't want to delete the article or vice versa, so I referenced user on_delete=models.DO_NOTHING in the Article model, but I am getting this error when I tried to delete a user, it seems to my that DO_NOTHING is not working the way I thought it does?How I can pass this and achieve what I tend to do without getting constrain error? Thanks

class Article(models.Model):
     title = models.CharField(max_length=355)
     author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, 
     related_name='articles')
     .....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绅士风度i 2025-02-09 18:06:46

您不能在大多数DB中参考现有的PK。如果您想在删除用户后离开文章,则应该执行这样的操作:

class Article(models.Model):
     title = models.CharField(max_length=355)
     author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, 
     related_name='articles')
 .....

这样,当您删除参考用户时,作者将被设置为db中的null。

You can't reference not existing PK in most of DBs. If you want to leave Article after deleting User you should do something like that:

class Article(models.Model):
     title = models.CharField(max_length=355)
     author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, 
     related_name='articles')
 .....

This way, when you are deleting referenceed user, author will be set to null in DB.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文