[Django]-Django failing to cascade-delete related generic foreign key object

6👍

rename field names of TaskLink

linked_content_type >>> content_type
linked_object_id >>> object_id

or write pre signal while deleting “Location” object to delete linked object “TaskLink”

from django.db.models.signals import pre_delete
from django.dispatch import receiver

@receiver(pre_delete, sender=Location, dispatch_uid='location_delete_signal')
def deleted_gfk_TaskLink(sender, instance, using, **kwargs):
    ctype = ContentType.objects.get_for_model(sender)
    obj = TaskLink.objects.get(linked_content_type=ctype, linked_object_id=instance.id)
    obj.delete()

reference for custom signals:
https://micropyramid.com/blog/using-djangos-built-in-signals-and-writing-custom-signals/

Leave a comment