问题描述
我在 Django(1.8.5) 中定义了以下模型:
I have the below models defined in Django(1.8.5):
class PublishInfo(models.Model):
pass
class Book(models.Model):
info = models.OneToOneField(
PublishInfo, on_delete=models.CASCADE)
class Newspaper(models.Model):
info = models.OneToOneField(
PublishInfo, on_delete=models.CASCADE)
其中 Book 和 NewsPaper
与 OneToOneField
共享相同的模型 PublishInfo
,这实际上是唯一的外键.
Where Book and NewsPaper
shares a same model PublishInfo
as a OneToOneField
, which is in fact a unique foreign key.
现在,如果我删除一个 PublishInfo
对象,相关的 Book
或 Newspaper
对象将被级联删除.
Now, if I delete a PublishInfo
Object, the relating Book
or Newspaper
object is deleted with cascading.
但实际上,当我删除Book
或Newspaper
对象时,我想删除PublishInfo
对象级联.这是我可以打电话的方式.
But in fact, I want to delete the PublishInfo
object cascading when I delete the Book
or Newspaper
object. This way is the way I may call.
在这种情况下,有没有什么好的方法可以在反向自动级联删除?如果是,能否解释一下?
Is there any good way to automatically cascading the deletion in the reverse direction in this case? And, if yes, could it be explained?
推荐答案
您附上 post_delete
向您的模型发送信号,以便在删除 Book
或 Newspaper
的实例时调用它:
You attach post_delete
signal to your model so it is called upon deletion of an instance of Book
or Newspaper
:
from django.db.models.signals import post_delete
from django.dispatch import receiver
@receiver(post_delete, sender=Book)
def auto_delete_publish_info_with_book(sender, instance, **kwargs):
instance.info.delete()
@receiver(post_delete, sender=Newspaper)
def auto_delete_publish_info_with_newpaper(sender, instance, **kwargs):
instance.info.delete()
这篇关于如何删除django中级联的一对一相关模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!