Posted by José Lopes.
In Django's administration panel the list_display option doesn't supports ManyToManyField fields, as you may confirm on the documentation. This is due because such field would entail executing a separate SQL statement for each row in the table.
The Django documentation suggests, if you want to have these fields visible, that we create a custom method and have it add to the list_display. Unfortunately there is no pratical example, or at least I haven't found one, so I wrote this post to provide such example.
Lets imagine that you have something like this on your models.py:
class Reference(models.Model):
something = models.CharField(max_length=100)
def __str__(self):
return self.something
class MyModel(models.Model):
other_thing = models.CharField(max_length=100)
references = models.ManyToManyField(Reference)
As you can see, the first class is a model with a character field while the second class is our model with the ManyToManyField.
Please remark the function on the first class used to pass the something records as string when called. Without this functions the records will not be visible on the administration panel neither on the views you may create.
To personalize the administration panel we usually do:
class MyModel(models.Model):
other_thing = models.CharField(max_length=100)
references = models.ManyToManyField(Reference)
class Admin:
list_display = ('other_thing', 'references')
Since we have a ManyToManyField on the list_display we'll get an error an the list will not be visible. The solution is to create a costum method and include it on the list_display like for instance:
class MyModel(models.Model):
other_thing = models.CharField(max_length=100)
references = models.ManyToManyField(Reference)
def show_references(self):
references = ", ".join([k.__str__() for k in self.references.all()])
return references
class Admin:
list_display = ('other_thing', 'show_references')
This costum method is nothing more than a function where we can group the information of the ManyToManyField in the way we find better. On this example we join all the instances of the field separated by commas.
Note that this function is then called inside the list_display instead of the ManyToManyField.
In this way you'll have the data of the ManyToManyField visible on the administration panel.