Helmi
Helmi

Reputation: 549

Django Admin list values from many to many fields

For a podcast site I do have a Guest model which (stripped down) looks like this.

class Guest(models.Model):
    ...
    episodes            = models.ManyToManyField(Episode)
    name                = models.CharField(max_length=100, blank=False)
    ...    

also there are a few other models connected through many to many fields with the guest model like Job and Topic (simple models with one or two CharField with some information and the ManyToManyField relation with Guest.

Now I want to display The Job(s) of a guest and his Topics in the Admin List of Guests. Also for the linked Episodes Model I want to count the amount of episodes a guest was in and also show the date (published_at field in Episode model) of the newest and the oldest Episode the guest was in.

I tried a few things already but I can't seem to get the data from the many to many fields into that list display. I'm on Django 2.0.7

Upvotes: 0

Views: 537

Answers (1)

Diego Vinícius
Diego Vinícius

Reputation: 2243

You cant just show, you make create one function and JOIN the values together...

class AdminGuest(admin.ModelAdmin):
    list_display = ('_episodes')

    def _episodes(self, obj):
        return "\n".join([a.nome for a in obj.episodes.filter()])
    _episodes.short_description = "List of Episodes"

Upvotes: 1

Related Questions