user1056978
user1056978

Reputation:

Django Deleting a GenericForeignKey

I am trying to implement an activity feed following this tutorial.

I would like to delete an acitivity(ie a comment has been added)when the corresponding object, ie the comment itself, has been removed. This doesn't seem to cascade.

Is there any way to achieve this without adding a GenericRelation? It is possible to delete the corresponding activity by using postdelete signal. Is that the best way?

Upvotes: 3

Views: 1858

Answers (1)

slamora
slamora

Reputation: 727

Yes you can, but maybe it's better using a pre_delete signal because you will be able to access to the instance 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()

Upvotes: 2

Related Questions