我有以下的在我的模型中定義:的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_type
和object_id
字段,而在我的情況下,字段不存在。這有效地限制了模型可能需要的通用外鍵的數量,除非您不會進行級聯刪除。
我通過Django郵件列表發送了這個問題,因爲這種行爲可能是故意的。
標記爲答案,因爲這解決了我的問題,但我認爲這很重要:Django h如果你打算依賴級聯刪除,並且通用外鍵防止模型擁有多個外鍵。 – Adam