zoukankan      html  css  js  c++  java
  • Django admin 后台 数据展示

    如果一个模型里包含了ManyToManyField或者ForeignKey,在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',)
    #设置哪些字段可以点击进入编辑界面,默认是第一个字段
    list_display_links('id')
    
    #由于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 = '标签'
    
  • 相关阅读:
    如何用Percona XtraBackup进行MySQL从库的单表备份和恢复【转】
    8款实用Sublime text 3插件推荐
    windows下配置nginx+php环境
    Windows10+Ubuntu双系统安装[
    window yii2 安装插件 报yiisoft/yii2 2.0.x-dev requires ext-mbstring错
    Composer常见问题
    Yii2中如何使用CodeCeption
    php 单进程SAPI生命周期
    php的SAPI,CLI SAPI,CGI SAPI
    HTTPS服务器配置
  • 原文地址:https://www.cnblogs.com/flyhgx/p/11354098.html
Copyright © 2011-2022 走看看