1

I am trying to access fields in the admin using list_display. According to the docs: (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display), ManyToManyFields are not supported. I have gotten around this by creating a custom method like this:

#models.py
class Gig
    musician = models.ManyToManyField(Musician)
    note = models.CharField(max_length=20)

    def __unicode__(self):
        return u'%s' % (self.note)

    def gig_musicians(self):
        return self.musician.all()

#admin.py
class GigAdmin
    list_display = ('note', 'gig_musicians')

This gives me the result I am looking for but it is very ugly (this works for generic relations too). The results look like:

    [<Musician: Richard Bona>, <Musician: Bobby Mcerrin>]

I think it is because of how I built the method. Do you have any advice for how to make this more elegant i.e. just the names?

I tried other solutions such as, django display content of a manytomanyfield, but i couldn't get it to work for me (it just displayed None)

Community
  • 1
  • 1
Nahanaeli Schelling
  • 1,235
  • 1
  • 12
  • 17

1 Answers1

5

Your current gig_musicians returns a QuerySet, not a string.

Try this gig_musicians function:

def gig_musicians(self):
   return ', '.join([obj.name for obj in self.musician.all()])
Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102
  • Thank you! This worked for most of my models. For a musician the name field is a OneToOne relation to an Individual i.e. `name = models.OneToOneField(Individual)` so when I used your code I got the error: expected string, Individual found. I tried to modify it to `([obj.individual.name for obj in self.musician.all()])` but that didn't work. Any advice? – Nahanaeli Schelling Oct 04 '12 at 22:59
  • update: I am getting this error for any field that is not a CharField – Nahanaeli Schelling Oct 04 '12 at 23:15
  • 1
    Your OneToOne Relation is little weird. Your musician should have a field like `individual = models.OneToOneField(Individual)`. If your individual model has a name field like `name = models.Charfield(...)` then your code will work. – Jingo Oct 04 '12 at 23:16
  • Ok, I'll use another example, if i have an address with a list of country choices. This solution does not work because it is getting a choice and not a string. – Nahanaeli Schelling Oct 05 '12 at 15:48
  • `gig_musicians.short_description = 'musicians'` for diffirent column name – WeizhongTu Jan 06 '16 at 06:49