user3220515
user3220515

Reputation: 51

Django was deleted parent relation when i delete child

I have two models:

class One(models.Model)
    name = models.CharField()

class Two(models.Model):
    one_first = models.OneToOneField(One, related_name='first', null=True, blank=True)
    one_second = models.OneToOneField(One, related_name='second', null=True, blank=True)

When I do two_instance.one_second.delete(), Django deletes the one instance (which I want), but it also deletes the two instance. Why does it delete two_instance?

Upvotes: 4

Views: 1187

Answers (1)

Alasdair
Alasdair

Reputation: 309099

For Django < 2.0, on_delete defaults to CASCADE. That means that when the two instance is deleted, the related one instance is deleted as well.

You can change this behaviour by using a different value for on_delete. For example, you could use on_delete=models.SET_NULL, which will set the value of the one-to-one field to None when the related object is deleted.

In your case, you have two one-to-one fields pointing to the same model, so you need to set on_delete for both fields.

class Two(models.Model):
    one_first = models.OneToOneField(One, on_delete=models.SET_NULL, related_name='first', null=True, blank=True)
    one_second = models.OneToOneField(One, on_delete=models.SET_NULL, related_name='second', null=True, blank=True)

Upvotes: 1

Related Questions