[英]Delete parent object when child object is deleted in Django
class A(models.Model):
name = models.CharField(max_length=128)
class B(modes.Model):
type_b = models.ForeignKey(A)
In a one-to-many relationship in Django, how do I delete the "one" object (model 'A') when I delete one of the related "many" objects (model 'B')?在 Django 的一对多关系中,当我删除相关的“多个”对象之一(模型“B”)时,如何删除“一个”对象(模型“A”)? I'm deleting the model 'B' object through the Django admin bulk delete option.
我正在通过 Django 管理批量删除选项删除模型“B”对象。
A best way to do it, just add [on_delete=models.CASCADE][1]
最好的方法是添加
[on_delete=models.CASCADE][1]
: :
class A(models.Model):
name = models.CharField(max_length=128)
class B(modes.Model):
type_b = models.ForeignKey(A,on_delete=models.CASCADE)
You can use post_delete signal to delete the parent as suggested by Davit Tovmasyan.您可以按照 Davit Tovmasyan 的建议使用 post_delete 信号删除父级。
BUT because of the cascading nature as the parent A object is deleted, it will also delete all the connected B objects which will inturn emit post_delete
signal on B model.但是由于父 A 对象被删除时的级联性质,它也将删除所有连接的 B 对象,这将反过来在 B 模型上发出
post_delete
信号。 So on the second emit of post_delete
the signal handler tries to delete an already deleted item which causes 'NoneType' object has no attribute 'delete'
.所以在
post_delete
的第二次发出时,信号处理程序试图删除一个已经删除的项目,这导致'NoneType' object has no attribute 'delete'
。 You can use exception handler or just use the if condition to handle this.您可以使用异常处理程序或仅使用 if 条件来处理此问题。
def delete_parent(sender, instance, **kwargs):
if instance.type_b:
instance.type_b.delete()
post_delete.connect(delete_parent, sender=B)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.