【问题标题】:FieldError trying to delete Django instances with generic foreign keyFieldError 试图使用通用外键删除 Django 实例
【发布时间】:2021-08-16 02:11:04
【问题描述】:

在修复一些错误的同时,我做了两个测试实例。现在我完成了,我想删除这两个测试:

nj.delete()
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'content_type' into field. Choices are: awards, career_highlights, content_object_org, content_object_pc, content_type_org, content_type_org_id, content_type_pc, content_type_pc_id, date_updated, daterange, end_date, honors, object_id_org, object_id_pc, org_history_updated, publications, role, significant_event, start_date, title, uniqid, updated_Vitae_bio_and_org_history

这个错误不是在我要删除的模型上,而是一个中间模型,它也有一个通用外键。 Django找不到'content_type'这个字段,因为没有这个字段,所以我不知道它为什么要找它。有一个 content_type_org 和一个 content_type_pc。从上下文中我假设 Django 想要 content_type_org。但是我如何告诉 Django 去寻找它呢?我也尝试去超类并从那里删除相同的对象,

jn.delete()

但遇到了同样的错误。

【问题讨论】:

  • 请分享模型的声明和您要删除的代码。

标签: python django generic-foreign-key


【解决方案1】:

正如 cmets 中所述,如果没有看到您的模型,就很难提供帮助。尽管如此,您似乎已经重命名了GenericForeignKey 中使用的content_type 字段。您需要使用 GenericRelation 在相关模型上指定重命名字段,如下所示:

class TaggedItem(models.Model):
    
    content_type_fk = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_primary_key = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type_fk', 'object_primary_key')


class Blog(models.Model):
    tags = GenericRelation(
        TaggedItem,
        content_type_field='content_type_fk',
        object_id_field='object_primary_key',
    )

详情请参阅docs

【讨论】:

  • 是的,丹尼尔,你完全正确。现在一切都解决了。非常感谢!
猜你喜欢
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多