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

相關問題