Django如何在用户删除后删除用户的个人资料和帖子以及所有关联?
我正在写一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当 Django 删除一个对象时,默认情况下它会模拟 SQL 约束 ON DELETE CASCADE 的行为——换句话说,任何具有指向要删除的对象的外键的对象都将随之删除。
https://docs.djangoproject.com/en/dev/topics/db/queries /#删除对象
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
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
在删除原始对象之前,您应该显式删除对原始对象的所有通用外键引用。例如,
级联删除在适用时非常有用,例如,对于模型中的一对一关系,但它似乎不适用于通用外键关系。
You should explicitly delete all of the generic foreign key references to the original object before you delete the original object. For example
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.