如果一個模型里包含了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 = '標簽'