2

我有以下的在我的模型中定义:的Django未能级联删除相关的通用外键对象

class TaskLink(models.Model): 
    task = model.ForeignKey(Task) 
    link_choices = (
     models.Q(app_label="accounts", model="location"), 
     # Other models are also linked to here. 
    ) 
    linked_content_type = \ 
     models.ForeignKey(
      ContentType, 
      limit_choices_to=link_choices 
     ) 
    linked_object_id = models.PositiveIntegerField() 
    linked_object = \ 
     generic.GenericForeignKey(
      'linked_object_content_type', 
      'linked_object_id' 
     ) 

这个模型链接Task对象与任何在link_choices元组的模型。在这种情况下,accounts.Location模型在此列表中。

当删除Location对象导致相关TaskLink对象级联删除时,我的问题就出现了。删除失败,出现以下错误消息:

django.core.exceptions.FieldError: Cannot resolve keyword 'object_id' into field. Choices are: id, linked_object, linked_object_content_type, linked_object_content_type_id, linked_object_id, task, task_id 

的视图是django.views.generic.DeleteView仅与pk_url_kwarg参数和模型组的实例(和权限装饰加入到调度方法);在我将TaskLink模型添加到混音中之前,它运行了linked_object_fine。

我错过了什么?

编辑:它似乎这可能是在Django中的错误;当通过泛型外键级联删除对象时,Django会忽略您传递给GenericForeignKey字段的构造函数的字段名称字符串,而不是看content_typeobject_id字段,而在我的情况下,字段不存在。这有效地限制了模型可能需要的通用外键的数量,除非您不会进行级联删除。

我通过Django邮件列表发送了这个问题,因为这种行为可能是故意的。

回答

2

TaskLink

的重命名字段名
linked_content_type >>> content_type 
linked_object_id >>> object_id 

或删除时, “位置” 对象删除链接对象 “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() 

定制信号的参考写预信号:
https://micropyramid.com/blog/using-djangos-built-in-signals-and-writing-custom-signals/

+0

标记为答案,因为这解决了我的问题,但我认为这很重要:Django h如果你打算依赖级联删除,并且通用外键防止模型拥有多个外键。 – Adam

相关问题