[英]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. 当我执行
two_instance.one_second.delete()
,Django会删除一个实例(我想要的),但它也会删除这两个实例。 Why does it delete two_instance
? 为什么删除
two_instance
?
For Django < 2.0, on_delete
defaults to CASCADE
. 对于Django <2.0,
on_delete
默认为CASCADE
。 That means that when the two
instance is deleted, the related one
instance is deleted as well. 这意味着当删除
two
实例时,也会删除相关的one
实例。
You can change this behaviour by using a different value for on_delete
. 您可以通过为
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. 例如,您可以使用
on_delete=models.SET_NULL
,它会在删除相关对象时将一对一字段的值设置为None
。
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. 在您的情况下,您有两个指向同一模型的一对一字段,因此您需要为这两个字段设置
on_delete
。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.