简体   繁体   中英

How to execute CASCADE on delete?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM