Django admin 后台 数据展示

如果一个模型里包含了ManyToManyField,在admin后台可能会显示成object,这时

class User_Tag(models.Model):
    user_tag = models.CharField(max_length=30,blank=True, verbose_name="标签")
    class Meta:
        db_table = "user_tag"
    def __unicode__(self):
        return self.user_tag
#新加上这个就行了
    def __str__(self):
        return self.user_tag

常见设置

  '''设置列表可显示的字段'''
    list_display = ('title', 'author',  'status', 'mod_date',)
    '''设置过滤选项'''
    list_filter = ('status', 'pub_date', )

    '''每页显示条目数'''
    list_per_page = 5

    '''设置可编辑字段'''
    list_editable = ('status',)

    '''按日期月份筛选'''
    date_hierarchy = 'pub_date'

    '''按发布日期排序'''
    ordering = ('-mod_date',)

#由于Django admin默认的多对多关系(ManyToMany)选择器是复选框,非常的不好用。一个更好的方法是使用filter_horizontal或filter_vertical选项
 filter_horizontal

指定显示多对多中字段的值

# admin.py,其中Author表中的authors字段和Book表是多对多关系

from django.contrib import admin
from .models import Author, Book, Publisher


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    # 显示多对多字段
    # 定义一个方法,遍历book的authors,然后用列表返回
    def show_all_author(self, obj):
        return [a.name for a in obj.authors.all()]

    list_display = ['title', 'publisher', 'show_all_author']  # 用刚刚定义的方法的返回值替换authors的值


或者
    def show_all_tags(self, obj):
        tag_names = map(lambda x: x.user_tag, obj.tags.all())
            return ', '.join(tag_names)
#设置表头
      show_all_tags.short_description = '标签'

猜你喜欢

转载自www.cnblogs.com/flyhgx/p/11354098.html