Search code examples
djangodjango-modelsdjango-signals

pre_delete signal error


I want to delete all Generic Foreign Key relationships belonging to a Contact when said contact is deleted.

This is what I have tried so far:

@receiver(pre_delete, sender=Contact):

    def contact_delete(sender, instance, **kwargs):
        from unsubscribe.models import Unsubscribe
        unsubscribe_list = Unsubscribe.objects.filter(object_id=instance)

        for item in unsubscribe_list:
            item.delete()

My issues are, how do I get the object_id of the instance. I only want to delete the related items of the object I'm deleting?


Solution

  • instance is the Contact object here. So, instance.id would give you the id of the contact object

    from django.db.models.signals import pre_delete
    from django.dispatch import receiver
    
    @receiver(pre_delete, sender=Contact, dispatch_uid='<whatever>')
    def contact_delete(sender, instance, using, **kwargs):
        from unsubscribe.models import Unsubscribe
        unsubscribe_list = Unsubscribe.objects.filter(object_id=instance.id, content_type__model='contact')
    
        for item in unsubscribe_list: #This should be a single element in the queryset. 
            item.delete()