How to execute CASCADE on delete?

拟墨画扇 提交于 2019-12-11 11:17:57

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/30518638/how-to-execute-cascade-on-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!