扩展Django admin的list_filter()可使用范围
2018-03-09 18:46
666 查看
需求描述
有时候我们会基于已有数据生成一列在表格中,类似于下面的class BaseSchema(models.Model): ... def test_status(self): # pdb.set_trace() if datetime.date.today() < self.test_start_date: return '未到测试区间' elif self.test_end_date and datetime.date.today() > self.test_end_date: return format_html('<p style="color: red">已下线</p>') else: return format_html('<p style="color: green">进行中</p>') test_status.short_description = u'测试状态'
但同时我们也希望可以对这一列进行筛选,按常规的话也就是添加到list_filter中:
list_filter = ('test_status')
这时候我们会看到django的温馨报错:
The value of 'list_filter[0]' refers to 'test_status', which does not refer to a Field.
也就是说不能使用list_filter对非Field进行筛选。
解决办法
最简单的方法
那就是把这个字段记录进field啊,这样就可以用了。但是我并不想这么做更高端的方法
参考https://stackoverflow.com/questions/12102697/creating-custom-filters-for-list-filter-in-django-admin/45136544#45136544第二个回答中的事例:from django.contrib.admin import SimpleListFilter class CountryFilter(SimpleListFilter): title = 'country' # or use _('country') for translated title parameter_name = 'country' def lookups(self, request, model_admin): countries = set([c.country for c in model_admin.model.objects.all()]) return [(c.id, c.name) for c in countries] + [ ('AFRICA', 'AFRICA - ALL')] def queryset(self, request, queryset): if self.value() == 'AFRICA': return queryset.filter(country__continent='Africa') if self.value(): return queryset.filter(country__id__exact=self.value()) class CityAdmin(ModelAdmin): list_filter = (CountryFilter,)
现在我们知道django中是这样实现的筛选的方法,那我们只要覆盖这个方法就好了:
class StatusFilter(SimpleListFilter): title = 'status' parameter_name = 'status' def lookups(self, request, model_admin): return [(1, '已下线'), (2, '进行中'), (3, '未到测试区间')] def queryset(self, request, queryset): this_day = datetime.date.today() # pdb.set_trace() if self.value() == '3': return queryset.filter(test_start_date__gt=this_day) elif self.value() == '1': return queryset.filter(test_end_date__lt=this_day) elif self.value() == '2': return queryset.filter(test_end_date__gte=this_day, test_start_date__lte=this_day)
然后在添加进list_filter中:
list_filter = (StatusFilter,)
bingo!
相关文章推荐
- django 自定义 admin的list_filter
- django admin 或xdmin list_display search_fields list_filter 如果显示搜索外键或多对多字段
- Django使用Profile扩展User模块
- Python list--> Filter , Map , Reduce 使用笔记 (lambda )
- PythonWeb开发Django框架学习(十一)使用框架自带Admin管理数据库数据
- 使用扩展方法将datatable化成list,list转成datatable
- 2.4.1、Django使用内置的Admin管理用户
- EXTJS4扩展实例:如何使用filter查询treepanel
- Android开发之ExpandableListView扩展(BaseExpandableListAdapter的使用)(完整版)
- MINA黑名单BlacklistFilter 使用
- 无法使用Django新建项目:'django-admin.py'不是内部或外部命令
- django中自定义admin中change_list.html中字段的显示
- Django 1.11 admin管理使用tinymce富文本编辑器
- django 自定义filter 判断if var in list
- 使用苹果airport路由器的WDS功能扩展wifi覆盖范围的设置方法
- 在Django中自定义filter并在template中使用
- Django中使用 admin 界面
- django 简易博客开发 1 安装、创建、配置、admin使用
- 为django 1.7 admin后台添加模板(使用django-suit)
- [Django1.4]admin模块使用出现Related Field has invalid lookup: icontains的错误