1

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

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

@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。我只想删除我正在删除的对象的相关项目?

4

1 回答 1

1

instanceContact这里的对象。所以,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()
于 2013-07-09T15:37:22.350 回答