Django:显示管理界面中许多项目的列表 [英] Django: show list of many to many items in the admin interface

查看:210
本文介绍了Django:显示管理界面中许多项目的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但我似乎无法理解。

This might be a simple question, but i can't seem to grasp it.

我在models.py中有两个简单的模型:服务和主机。 Host.services与Service具有m2m关系。
换句话说,主机有几个服务,一个服务可以驻留在多个主机上;一个基本的m2m。

I have two simple models in models.py: Service and Host. Host.services has a m2m relationship with Service. In other words, a host has several services and one service can reside on multiple hosts; a basic m2m.

models.py

models.py

class Service(models.Model):
    servicename = models.CharField(max_length=50)

    def __unicode__(self):
            return self.servicename

    class Admin:
            pass

class Host(models.Model):
    #...
    hostname = models.CharField(max_length=200)
    services = models.ManyToManyField(Service)
    #...

    def get_services(self):
            return self.services.all()

    def __unicode__(self):
            return self.hostname

    class Admin:
            pass

admin.py

from cmdb.hosts.models import Host
from django.contrib import admin


class HostAdmin(admin.ModelAdmin):

    list_display = ('get_services',)

admin.site.register(Host, HostAdmin)

现在,当我打开所有主机列列出的页面,服务列显示如下输出:

Now when i open the page where all the host's columns are listed the 'service' column displays the output like:

获取服务

[< Service:the_service-1>< Service:the_service-2>]

的:

服务

the_service-1

the_service-1

the_service-2
等。

the_service-2 etc.

我做错了什么?
感谢您阅读我的问题。

What am i doing wrong? Thank you for reading my question.

推荐答案

您应该更改 get_services 如下:

def get_services(self):
    return "\n".join([s.servicename for s in self.services.all()])

更新: 尝试使用 \\\
作为分隔符,而不是< br /> 作为输出get_services正在被转义。

Update: Try using \n as the separator rather than <br/>, as the output of get_services is being escaped.

这篇关于Django:显示管理界面中许多项目的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆