重新定义admin.py中的Hero管理模型如下:
python
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin):
list_display = ("name", "is_immortal", "category", "origin", "is_very_benevolent")
list_filter = ("is_immortal", "category", "origin",)
def is_very_benevolent(self, obj):
return obj.benevolence_factor > 75
它具有一个计算字段is_very_benevolent,Admin后台显示如下:
我们已经在来自模型属性字段上添加了过滤,但是还想在计算出的字段上添加过滤。为此,我们可以通过继承SimpleListFilter类实现:
python
class IsVeryBenevolentFilter(admin.SimpleListFilter):
title = 'is_very_benevolent'
parameter_name = 'is_very_benevolent'
def lookups(self, request, model_admin):
return (
('Yes', 'Yes'),
('No', 'No'),
)
def queryset(self, request, queryset):
value = self.value()
if value == 'Yes':
return queryset.filter(benevolence_factor__gt=75)
elif value == 'No':
return queryset.exclude(benevolence_factor__gt=75)
return queryset
然后将更改list_filter为list_filter = ("is_immortal", "category", "origin", IsVeryBenevolentFilter)
这样,便可以对计算出的字段进行过滤。修改后管理后台显示如下:
如何对计算字段修改成系统自带的布尔类型显示效果,增加is_very_benevolent.boolean = True代码,HeroAdmin管理模型修改如下:
python
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin):
list_display = ("name", "is_immortal", "category", "origin", "is_very_benevolent")
list_filter = ("is_immortal", "category", "origin", IsVeryBenevolentFilter)
def is_very_benevolent(self, obj):
return obj.benevolence_factor > 75
is_very_benevolent.boolean = True
显示效果如下: