class Ghost(models.Model): create = models.DateTimeField(default=timezone.now, help_text='创建时间') update = models.DateTimeField(auto_now=True, help_text='修改时间') speed = models.IntegerField(default=0, help_text='速度') name = models.CharField(max_length=64, help_text='名称') class InstanceTask(models.Model): create = models.DateTimeField(default=timezone.now, help_text='创建时间') update = models.DateTimeField(auto_now=True, help_text='修改时间') name = models.CharField(max_length=64, help_text='副本名称') class InstanceTaskMap(models.Model): create = models.DateTimeField(default=timezone.now, help_text='创建时间') update = models.DateTimeField(auto_now=True, help_text='修改时间') name = models.CharField(max_length=64, help_text='地图名称') ghosts = models.ManyToManyField(Ghost, help_text='Ghost') instance_task = models.ForeignKey(InstanceTask, related_name='instancetask_instancetaskmap', blank=True, null=True, help_text='副本任务', on_delete=models.SET_NULL) |
对于上面的model,如果要在django admin中展示ghosts信息,那么在list_display中直接加入’ghosts’ 会报下面的错误:The value of ‘list_display[1]’ must not be a ManyToManyField.
如果要解决这个问题可以使用下面的代码来展示:
class InstanceTaskMapAdmin(admin.ModelAdmin): list_display = ('name', 'instance_task', 'id', 'index', 'get_ghost_name', 'introduction') # https://blog.csdn.net/weixin_42134789/article/details/83686664 def get_ghost_name(self, obj): ghost_list = [] for g in obj.ghosts.all(): ghost_list.append(g.ghost.name) return ','.join(ghost_list) get_ghost_name.short_description = "Ghosts" |
如果需要更丰富的信息可以参考上面代码注释中的链接。
对于foreignkey同样可以使用这样的方式进行反向查询展示所有相关的model。
例如要在InstanceTask页面展示所有的InstanceTaskMap,可以使用下面的代码:
class InstanceTaskAdmin(admin.ModelAdmin): list_display = ('name', 'id', 'need_level', 'times_limit', 'instance_type','get_map_list', 'introduction') def get_map_list(self, obj): map_list = [] for g in obj.instancetask_instancetaskmap.all().order_by('index'): map_list.append(g.name + '(' + str(g.index) + ')') return ','.join(map_list) get_map_list.short_description = "Maps" |
原创文章,转载请注明: 转载自 obaby@mars
本文标题: 《Django admin Foreignkey ManyToMany list_display展示》
本文链接地址: http://h4ck.org.cn/2019/12/django-admin-foreignkey-manytomanykey-list_display%e5%b1%95%e7%a4%ba/