Xinghan
Xinghan

Reputation: 255

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

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?

Upvotes: 9

Views: 13612

Answers (3)

jdickson
jdickson

Reputation: 724

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

Upvotes: 7

Mark Chackerian
Mark Chackerian

Reputation: 23582

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.

Upvotes: 5

Priyeshj
Priyeshj

Reputation: 1345

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

Upvotes: 14

Related Questions