我像进行年月筛选, 选择年月的话,就可以筛选出这个年月的所有记录,例如我只需要输入2024-06就可以显示出2024-06-01到2024-06-30的范围
我的filter.py
class ConsumeDetailsFilter(FilterSet):
# date = filters.DateFilter(field_name='date')
start_date = filters.DateFilter(field_name='date', lookup_expr='gte', label='Start Date')
end_date = filters.DateFilter(field_name='date', lookup_expr='lte', label='End Date')
category = filters.CharFilter(field_name='category', lookup_expr='icontains')
subcategory = filters.CharFilter(field_name='subcategory', lookup_expr='icontains')
vendor = filters.CharFilter(field_name='vendor', lookup_expr='icontains')
item = filters.CharFilter(field_name='item', lookup_expr='icontains')
class Meta:
model = ConsumeDetails
fields = ['start_date','end_date','category', 'subcategory']
我的 views.py
class ConsumeDetailsViewSet(ModelViewSet):
queryset = ConsumeDetails.objects.all()
serializer_class = ConsumeDetailsSerializer
# filter_backends = (DjangoFilterBackend,) #在settings.py里面做了全局添加。这里可以不需要
# filter_class = ConsumeDetailsFilter # 这个方法在django-filter 21.1 以上版本中已经废弃,视频教程是这个方法。
# filterset_fields = ['consumepurpose','consumetype','category','subcategory']
filterset_class = ConsumeDetailsFilter
filterset_fields = ['start_date', 'end_date'] #'consumepurpose', 'consumetype', 'category', 'subcategory'
pagination_class = MyPageNumberPagination
# filter_backends = (SearchFilter,) #在settings.py里面做了全局添加。这里可以不需要
search_fields = ['category','subcategory','vendor','item']