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"