1

I have this model in Django, where a person has the same information from the user provided by Django plus a little bit more information. When I create a new person it requires to create a new user also, that's fine. But when I delete a person the user still remains on my database. What am I missing here ? I would like to delete the user too.

class Person(models.Model):
    user = OneToOneField(User)
    gender = CharField(max_length=1, choices=GenderChoices, blank=True, null=True)
    birth_date = DateField(blank=True, null=True)

    def __unicode__(self):
        return self.user.username
Valter Silva
  • 16,446
  • 52
  • 137
  • 218
  • What does the SQL `CASCADE` instruction do? I've found some relevant documentation about it's usage in Django here: https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey.on_delete – SebasSBM May 28 '15 at 23:46

1 Answers1

0

Try to override the delete method on the model (code not tested):

class Person(models.Model):
    user = OneToOneField(User)
    gender = CharField(max_length=1, choices=GenderChoices, blank=True, null=True)
    birth_date = DateField(blank=True, null=True)

    def __unicode__(self):
        return self.user.username

    def delete():
        theuser = User.objects.get(id=user)
        theuser.delete()

I have found some relevant documentation about CASCADE usage in Django here.

SebasSBM
  • 860
  • 2
  • 8
  • 32
  • Thank you for your answer Sebas, but I think that if I override the delete method I might find some problems with the bulk operations: http://stackoverflow.com/a/16621653/523168 – Valter Silva May 28 '15 at 23:30
  • Maybe you can use `pre_delete` and `post_delete` signals to create events that handle that issue properly... I haven't played around with signals yet. – SebasSBM May 28 '15 at 23:34