Reputation: 1317
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.
Upvotes: 2
Views: 2183
Reputation: 11083
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.
Upvotes: 3