首页 > 解决方案 > 如何在“字段”元组中包含外键字段以使其显示在 Django Admin 的详细视图页面上

问题描述

模型: 我有一个这样的模型

class TestModel1(models.Model):
    bookingid = models.ForeignKey(paymenttable)            // foreign key
    name = models.CharField(max_length=100, null=False, db_index=True)

    // I want this to be displayed in both the list view and detail view
    @property
    def custom_field(self):
       return self.bookingid.username  

管理员.py

class MyAdmin(ReadOnlyAdminFields,admin.ModelAdmin):

      // this works and i get custom_field in list view
      list_display = ('custom_field', 'name') 
      readonly = ('custom_field', 'name')

      // this dosent work and gives error  
      fields = ('custom_field', 'name')   

错误:未知字段 custom_field。检查 MyAdmin 类的字段/字段集/排除属性

标签: pythondjangopython-2.7django-modelsdjango-admin

解决方案


你有一个小错字。readonly应该readonly_fields

一个小技巧,你可以在你的方法中添加一个带有short_description属性的自定义标签custom_field。你可以这样做...

# models.py

class TestModel1(models.Model):
    bookingid = models.ForeignKey(paymenttable)
    name = models.CharField(max_length=100, null=False, db_index=True)

    @property
    def custom_field(self):
       return self.bookingid.username

    custom_field.short_description = "User"

然后你可以像这样在管理类的字段列表中使用它......

# admin.py

class MyAdmin(ReadOnlyAdminFields,admin.ModelAdmin):
      list_display = ('custom_field', 'name') 
      readonly_fields= ('custom_field', 'name')
      fields = ('custom_field', 'name')   

推荐阅读