django admin显示相关模型的字段

时间:2017-02-10 18:41:31

标签: django django-models django-admin django-import-export

我想在ip_address的管理显示中显示Hosts模型中的HostInfo

# models.py
class Hosts(models.Model):
  host_name = models.CharField(max_length=200, unique=True)
  ip_address = models.GenericIPAddressField(protocol='both', unpack_ipv4=True)
  def __unicode__(self):
    return unicode(self.host_name)
  def hostip(self):
    return unicode(self.ip_address)

我在admin.py

中有以下内容
# admin.py
class HostInfoResource(resources.ModelResource):

    host = fields.Field(column_name='host',
                              attribute='host',
                              widget=ForeignKeyWidget(Hosts, 'host_name'))
    project = fields.Field(column_name='project',
                                attribute='project',
                                widget=ForeignKeyWidget(Project, 'project_name'))
    env = fields.Field(column_name='env',
                            attribute='env',
                            widget=ForeignKeyWidget(Env, 'env_name'))

    class Meta:
        model = HostInfo
        skip_unchanged = True
        import_id_fields = ('id', 'host','ticket','deployed_by')
        export_order = ('id', 'host', 'nexpose_level','cpus','memory','os',
                        'sudoers_copied', 'sudo_granted', 'extra_disks','app_type','app_name',
                        'vcenter_status','ticket','env','project','deployed_by',
                        'updated_on','created_on')

class HostInfoAdmin(ImportExportModelAdmin):
    resource_class = HostInfoResource
    list_display = ['id', 'host', 'nexpose_level','cpus','memory','os',
                        'sudoers_copied', 'sudo_granted', 'extra_disks','app_type','app_name',
                        'vcenter_status','ticket','env','project','deployed_by']

    readonly_fields = ('updated_on','created_on',)

admin.site.register(HostInfo, HostInfoAdmin)

我不太了解实现这一目标所需的条件。

1 个答案:

答案 0 :(得分:3)

如果想要嵌套在关系中,请尝试使用双下划线。

class HostInfoAdmin(ImportExportModelAdmin):
    resource_class = HostInfoResource
    list_display = ['id','host__ip_address', 'host', 'nexpose_level','cpus','memory','os',
                        'sudoers_copied', 'sudo_granted', 'extra_disks','app_type','app_name',
                        'vcenter_status','ticket','env','project','deployed_by'] 

    def host__ip_address(self, obj):
        return obj.host.ip_address