I have the following model:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User)
# ...
def __unicode__(self):
return u'%s %s' % (self.user.first_name, self.user.last_name)
When using the Django admin to delete the user, the profile gets deleted as well, which is what I want. However, when using the Django admin to delete the profile, the user does not get deleted, which is not what I want. How can I make it so that deleting the profile will also delete the user?
Since
Profilelinks toUser, it is the dependent model in the relationship. Therefore when you delete a user, it deletes all dependent models. However when you delete a profile, sinceUserdoes not depend on profile, it is not removed.Unfortunately, according to
on_deleteDjango docs, there is noon_deleterule which deletes the parent relations. In order to do that, you can overwrite theProfile‘sdeletemethod:Then when doing:
will also delete the profile’s user. However the
deletemethod will not be called when deleting profiles using querysets (which is what is called in Django Admin) since then Django uses SQL DELETE to delete objects in bulk:In that case, as recommended by Django docs, you will have to use
post_deletesignal (docs).