Django如何在用户删除后删除用户的个人资料和帖子以及所有关联?

发布于 2024-12-29 01:14:32 字数 125 浏览 1 评论 0原文

我正在写一个 django 项目。并想知道用户删除自己的帐户后,django内置是否有一种方法可以自动删除与该用户相关的所有对象(例如一些通用的foreign_key)?或者我应该使用信号“post_delete”来删除所有相关的对象?

I'm writing a django project. And want to know after user deletes his own account, is there a way django build-in to auto delete all object related to this user(e.g. some generic foreign_key)? Or I should use signal "post_delete" to delete every objects related?

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

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

发布评论

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

评论(3

酒废 2025-01-05 01:14:32

当 Django 删除一个对象时,默认情况下它会模拟 SQL 约束 ON DELETE CASCADE 的行为——换句话说,任何具有指向要删除的对象的外键的对象都将随之删除。

https://docs.djangoproject.com/en/dev/topics/db/queries /#删除对象

b = Blog.objects.get(pk=1)
# This will delete the Blog and all of its Entry objects.
b.delete()

When Django deletes an object, by default it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.

https://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects

b = Blog.objects.get(pk=1)
# This will delete the Blog and all of its Entry objects.
b.delete()
可爱咩 2025-01-05 01:14:32

Django 建议不要删除用户,因为外键会损坏。正是由于这个原因,他们包含了 is_active 方法。

请参阅 https://docs.djangoproject .com/en/1.3/topics/auth/#django.contrib.auth.models.User.is_active

Django recommends not deleting users since foreign keys will break. It's for this reason that they included the is_active method.

See https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.models.User.is_active

欢烬 2025-01-05 01:14:32

在删除原始对象之前,您应该显式删除对原始对象的所有通用外键引用。例如,

Image.objects.filter( object_id=object_to_be_deleted.id,content_type = ContentType.objects.get_for_model(bject_to_be_deleted.get_profile() )).delete()
object_to_be_deleted.delete()

级联删除在适用时非常有用,例如,对于模型中的一对一关系,但它似乎不适用于通用外键关系。

You should explicitly delete all of the generic foreign key references to the original object before you delete the original object. For example

Image.objects.filter( object_id=object_to_be_deleted.id,content_type = ContentType.objects.get_for_model(bject_to_be_deleted.get_profile() )).delete()
object_to_be_deleted.delete()

The cascading delete is great when it works, for example, for one-to-one relationships in the models, but it doesn't seem to work for generic foreign key relationships.

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