【问题标题】:pre_delete signal errorpre_delete 信号错误
【发布时间】:2013-07-09 15:32:10
【问题描述】:

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

这是我迄今为止尝试过的:

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

【问题讨论】:

  • 你试过instance.pk吗?

标签: django django-models django-signals


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2014-12-05
    • 1970-01-01
    • 2016-05-02
    • 2020-04-23
    相关资源
    最近更新 更多