django的ManyToManyField字段在admin后台上显示方法

一、数据库模型代码

需将 tag = models.ManyToManyField(Tag, verbose_name=‘标签’)的多个字段显示在后台上的model.py代码

# 文章内容表
class Post(models.Model):
    STATUS_NORMAL = 1
    STATUS_DELETE = 0
    STATUS_DRAFT = 2
    STATUS_ITEMS = (
        (STATUS_NORMAL, '正常'),
        (STATUS_DELETE, '删除'),
        (STATUS_DRAFT, '草稿')
    )
    title = models.CharField(max_length=255, verbose_name='标题')
    desc = models.TextField(verbose_name='摘要')
    content = models.TextField(verbose_name='正文', help_text='正文必须为MarkDown格式')
    status = models.PositiveIntegerField(default=STATUS_NORMAL, choices=STATUS_ITEMS, verbose_name='状态')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='分类')
    tag = models.ManyToManyField(Tag, verbose_name='标签')
    owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

二、admin.py代码

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    def post_tag(self, obj):
        return [pt.name for pt in obj.tag.all()]

    post_tag.short_description = '标签'
	list_display = ['title', 'category', 'post_tag', 'status','created_time', 'owner', 'operator'] 			             

三、运行结果

django的ManyToManyField字段在admin后台上显示方法_第1张图片

如图所示,在后台的标签中就可以显示多个标签了啦!

你可能感兴趣的:(django开发,博客开发,django,python,后端)