3

我正在尝试按照本教程实施活动提要。

当相应的对象(即评论本身)已被删除时,我想删除一个活动(即已添加评论)。这似乎没有级联。

有没有办法在不添加 GenericRelation 的情况下实现这一点?可以使用 postdelete 信号删除相应的活动。这是最好的方法吗?

4

1 回答 1

1

是的,您可以,但使用pre_delete 信号可能会更好,因为您将能够访问实例 pk。

from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_delete
from django.dispatch import receiver

from yourapp.models import Comment, Activity

@receiver(pre_delete, sender=Comment)
def pre_delete_receiver(sender, instance,**kwargs):
    # code that delete the related objects
    # As you don't have generic relation you should manually
    # find related actitities
    ctype = ContentType.objects.get_for_model(instance)
    Activity.objects.filter(content_type=ctype, object_id=instance.pk).delete()
于 2014-05-14T14:02:27.167 回答