Django how to delete user's profile and posts and all assocation after user deleted?

Xinghan picture Xinghan · Jan 25, 2012 · Viewed 12.4k times · Source

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?

Answer

Priyeshj picture Priyeshj · Jan 26, 2012

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()