除了以前的答案 - 如果你有更复杂的结构和类似的东西GenericOneToOne
(在 Django 中没有直接出现):
class Post(models.Model)
title = models.CharField(max_length=100)
class Comment(models.Model):
post = models.ForeignKey(Post)
body = models.TextField(verbose_name='Comment')
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Meta:
# Constrain equals to OneToOne relation.
unique_together = ('content_type', 'object_id')
class Author(models.Model):
comment = GenericRelation(Comment)
name = models.CharField(max_length=100)
你想删除Post
并确保它Comment
也Author
被删除,你需要编写自定义post_delete
信号:
from django.db.models.signals import post_delete
from django.dispatch import receiver
@receiver(post_delete, sender=Comment, dispatch_uid='delete_comment_content_object')
def delete_comment_content_object(sender, instance, using, **kwargs):
instance.content_object.delete()
如果您像这样覆盖类delete
的方法Comment
:
def delete(self, *args, **kwargs):
self.content_object.delete()
super().delete(args, kwargs)
Author
只有你删除它才会删除Comment
。如果您删除Post
Author
对象将保留在数据库中。