tags:

views:

87

answers:

1

Hi,

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

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

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:

Get services

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

Instead of:

Services

the_service-1

the_service-2 etc.

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

+2  A: 

You should change get_services to something like:

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

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

Vinay Sajip
+1. Wish there was a better way to do this than hardcoding HTML formatting in a model method.
Andre Miller
It's just one way. Another would be to render a template to string and return the result - this would move the HTML to the template. However, this is for the Django admin - which is for sysadmins rather than end-users - hence maybe the utilitarian approach is OK.
Vinay Sajip
Thank you, the answer did the trick.
Bas van der Zon