我在Django的后台通过TabularInline
列出一个模型。在这个内联(inline)中,我想使用Django的模型遍历语法来列出通过外键引用该模型的其他模型中的数据。例如:
class MyRelatedModel(models.Model):
name = models.CharField(max_length=50)
created = models.DateField(auto_now_add=True)
other = models.ForeignKey('MyOtherRelatedModel')
class MyOtherRelatedModel(models.Model):
name = models.CharField(max_length=50)
created = models.DateField(auto_now_add=True)
class MyRelatedModelInline(admin.TabularInline):
model = MyRelatedModel
fields = ['name', 'created', 'other__name']
#readonly_fields = ['name', 'created', 'other__name']
然而,使用 'other__name' 会抛出 ImproperlyConfigured 错误:
'MyRelatedModelInline.fields' refers to field 'other__name' that is missing from the form
模型遍历语法在ModelAdmin实例中是否不受支持?如果支持,那么我做错了什么?
编辑:如果我取消注释readonly_fields,错误会变成:
Caught AttributeError while rendering: 'MyMainModelAdmin' object has no attribute '__name__'