Django GenericTabularInline:(admin.E302)' ct_field'引用' content_type',这不是字段

时间:2015-08-29 22:13:40

标签: django

我正在尝试使用Generic Foreign Keys的模型(Prereq)出现在MyModel的管理员中。

models.py:

class MyModel(models.Model):
    name = models.CharField(max_length=50, unique=True)
    #etc

class Prereq(models.Model):
    parent_content_type = models.ForeignKey(ContentType, related_name='prereq_parent')
    parent_object_id = models.PositiveIntegerField()
    parent_object = GenericForeignKey("parent_content_type", "parent_object_id")

    prereq_content_type = models.ForeignKey(ContentType, related_name='prereq_item')
    prereq_object_id = models.PositiveIntegerField()
    prereq_object = GenericForeignKey("prereq_content_type", "prereq_object_id")
    prereq_invert = models.BooleanField(default=False, help_text = 'parent is available if user does NOT have this pre-requisite')

    or_prereq_content_type = models.ForeignKey(ContentType, related_name='or_prereq_item', blank=True, null=True)
    or_prereq_object_id = models.PositiveIntegerField(blank=True, null=True)
    or_prereq_object = GenericForeignKey("or_prereq_content_type", "or_prereq_object_id")
    or_prereq_invert = models.BooleanField(default=False, help_text = 'parent is available if user does NOT have this pre-requisite')`

Admin.py:

class PrereqInline(GenericTabularInline):
    model = Prereq
    fk_name = "prereq_parent" #tried "parent_object" also

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('name', ...etc)
    inlines = [
        PrereqInline,
    ]

admin.site.register(MyModel, MyModelAdmin)

如何解决我遇到的错误?

<class 'my_app.admin.PrereqInline'>: (admin.E302) 'ct_field' references 'content_type', which is not a field on 'my_app.Prereq'.

1 个答案:

答案 0 :(得分:7)

想出来:

GenericTabularInline要求添加ct_fieldct_fk_field,因为这些字段未分别使用默认名称content_typeobject_id

class PrereqInline(GenericTabularInline):
    model = Prereq
    ct_field = "parent_content_type"
    ct_fk_field = "parent_object_id"
    fk_name = "parent_object"