简体   繁体   中英

Django Delete OneToOneField

I'm creating a Django web-app. I have an app named vote . I want to "register" this app via a OneToOne-Relationship to other apps. For example, I have an article app and I want to "register" vote:

vote = models.OneToOneField(Vote, on_delete=models.CASCADE, default=None, null=True)

I changed the save method on article:

def save(self, *args, **kwargs):
    self.vote = Vote.objects.create()
    super().save(*args, **kwargs)

Here's the problem: I want the vote to be deleted when I delete article but that doesn't work. When I delete article only article will be deleted and vote still exists.

That is correct behavior. you want to delete an article and want its votes to be deleted. so you should put your relation(One to One) on the Vote model, not the article. So replace:

vote = models.OneToOneField(Vote, on_delete=models.CASCADE, default=None, null=True)

To:

article = models.OneToOneField(Article, on_delete=models.CASCADE)

But on the vote model.

Note that: do not use default and null on this case.

Also, you can read this Link to understand where to put a relation and how cascade will delete it.

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