Django admin Foreignkey ManyToMany list_display展示

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
* 网址:https://h4ck.org.cn/
* 个性:https://oba.by/
* 本文标题: 《Django admin Foreignkey ManyToMany list_display展示》
* 本文链接:https://h4ck.org.cn/2019/12/6664
* 短链接:https://oba.by/?p=6664
* 转载文章请标明文章来源,原文标题以及原文链接。请遵从 《署名-非商业性使用-相同方式共享 2.5 中国大陆 (CC BY-NC-SA 2.5 CN) 》许可协议。


猜你喜欢:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注