我正在尝试根据日期和月份过滤日期。下面是我尝试过的。在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时,我得到的结果是空的。在这方面的任何帮助将不胜感激。
答案 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')