如何在模型中为dateField的月份/年份创建django-filter自定义过滤器?

时间:2019-01-22 16:46:58

标签: django django-rest-framework django-filter

我正在尝试根据日期和月份过滤日期。下面是我尝试过的。在models.py

class Expense(TimeStampedModel):date = models.DateField(_('date')

在serailizer.py

class ExpenseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Expense
        fields = '__all__'

在filters.py

class ExpenseFilter(django_filters.FilterSet):
    date__month = django_filters.DateFilter(field_name='date',                  
    lookup_expr='month')
    date__year = django_filters.DateFilter(field_name='date', lookup_expr='year')
    class Meta:
        model = Expense
        fields = ('date__month', 'date__year')

在views.py

class ExpenseViewSet(viewsets.ModelViewSet):
    queryset = Expense.objects.all()
    serializer_class = ExpenseSerializer
    filter_class = ExpenseFilter

当我尝试击中post时,我得到的结果是空的。在这方面的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您是否考虑过使用DateRangeFilter?对于您来说,这可能是一个更好的选择。它不会做什么,但是您建议的ExpenseFilter是查找所有年份一个月的费用实例。

答案 1 :(得分:0)

class CustomDateFilter(DateFilter):
def filter(self, qs, value):
    if value:
        filter_lookups = {
            "%s__month" % (self.field_name, ): value.month,
            "%s__year" % (self.field_name, ): value.year
        }
        qs = qs.filter(**filter_lookups)
    return qs

Class ExpenseDateFilter(FilterSet):     日期= CustomDateFilter(field_name ='date')

class Meta:
    model = Expense
    fields = ('project__id', 'date')