Django未能级联删除相关的通用外键对象
我在模型中定义了以下内容:Django未能级联删除相关的通用外键对象,django,cascade,django-class-based-views,generic-foreign-key,Django,Cascade,Django Class Based Views,Generic Foreign Key,我在模型中定义了以下内容: 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 = \ mod
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\u选项
元组中的任何模型链接起来。在本例中,accounts.Location
模型在此列表中
当删除位置
对象导致级联删除相关的任务链接
对象时,我的问题就出现了。删除失败,并显示以下错误消息:
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\u url\u kwarg
参数和模型集(以及添加到分派方法中的权限装饰器);在我将TaskLink
模型添加到混合之前,它工作得很好
我错过了什么
编辑:看起来这可能是Django中的一个bug;当通过泛型外键级联删除对象时,Django会忽略传递给GenericForeignKey
字段构造函数的字段名字符串,而是查找content\u type
和object\u id
字段,在我的例子中,这些字段并不存在。这有效地限制了一个模型可能必须拥有的通用外键的数量为1,除非您不会遇到级联删除
我已经通过Django邮件列表发送了此问题,因为这种行为可能是故意的。重命名TaskLink的字段名
linked_content_type >>> content_type
linked_object_id >>> object_id
或在删除“位置”对象时写入预信号以删除链接对象“任务链接”
自定义信号参考:标记为答案,因为这解决了我的问题,但我认为需要注意的是:Django处理通用外键的方式防止模型具有多个外键,如果您打算依赖级联删除。
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()