class warehousePeopleBase(ModelAdmin): model = warehousePeople menu_label = '库房人员出入库信息' # ditch this to use verbose_name_plural from model menu_icon = 'site' # change as required list_display = ['name', 'yearMonth', 'month', 'warehouse', 'subjectMatter'] list_filter = ('name', 'yearMonth', 'month', 'warehouse',) wagtail怎么将右侧过滤器的yearMonth字段更改为可以任意的选择年份和月份?
时间: 2023-12-22 18:02:54 浏览: 118
你通过自定义`list_filter`来实现这个功能。具体步骤如下:
1. 定义一个自定义的Filter类,继承`django.contrib.admin.SimpleListFilter`类,重写`queryset`和`lookups`方法,来实现筛选功能。
```python
import datetime
class YearMonthFilter(admin.SimpleListFilter):
title = 'Year Month'
parameter_name = 'year_month'
def lookups(self, request, model_admin):
# 获取所有可以选择的年月列表
year_month_list = []
for obj in model_admin.model.objects.all():
year_month = obj.yearMonth.strftime('%Y-%m')
if year_month not in year_month_list:
year_month_list.append(year_month)
return [(ym, ym) for ym in year_month_list]
def queryset(self, request, queryset):
if self.value():
year_month = datetime.datetime.strptime(self.value(), '%Y-%m')
return queryset.filter(yearMonth=year_month)
```
2. 在`list_filter`中添加自定义的Filter类
```python
class warehousePeopleBase(ModelAdmin):
model = warehousePeople
menu_label = '库房人员出入库信息' # ditch this to use verbose_name_plural from model
menu_icon = 'site' # change as required
list_display = ['name', 'yearMonth', 'month', 'warehouse', 'subjectMatter']
list_filter = ('name', 'warehouse', YearMonthFilter)
```
这样就可以在右侧过滤器中选择任意年份和月份进行筛选了。
阅读全文