When I specified the ManyToManyField column in list_display of admin.py, I got the following error.
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'proj.admin.ArticleAdmin'>: (admin.E109) The value of 'list_display[2]' must not be a ManyToManyField.
I thought it would be convenient to be able to list the data of another table linked by ManyToManyField for a certain record on the management site, but it seems that the specification cannot be specified according to the error message.
However, it was possible by doing the following, so I will record the method.
Imagine an example where metadata is added to a document, such as Hatena Bookmark.
Suppose you have three authors, an Article, and a Tag.
Article.meta is ManyToManyField, and Tag is specified as the relation destination.
models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey('Author', blank=True, null=True)
meta = models.ManyToManyField('Tag')
def __unicode__(self):
return self.title
class Tag(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
admin.py
If you define a function with an arbitrary name such as _meta and specify the corresponding function name in list_display, you can list the data linked by commas as shown in the figure above.
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'author', '_meta')
def _meta(self, row):
return ','.join([x.name for x in row.meta.all()])
admin.site.register(Article, ArticleAdmin)
Recommended Posts