pre_delete信号错误

时间:2013-07-09 15:32:10

标签: django django-models django-signals

删除所述联系人时,我想删除属于联系人的所有通用外键关系

这是我到目前为止所尝试的:

@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()

我的问题是,如何获取实例的object_id。我只想删除我要删除的对象的相关项目?

1 个答案:

答案 0 :(得分:1)

instance是此处的Contact对象。因此,instance.id会为您提供联系对象的ID

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()