我在 Django 中按年和月过滤时遇到问题

时间:2021-06-17 10:07:06

标签: python django django-filter

我正在尝试按月份和日期过滤查询集

这是一个代码:

class FinalListView(generics.ListAPIView):
    serializer_class = FinalSerializer
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]

    def get_queryset(self):
        condition = Q()
        queryset = Final.objects.all()
        month = self.request.query_params.getlist('month')
        year = self.request.query_params.getlist('year')

    if month:
        if month != 'all':
            for a in month:
                condition |= Q(created_at__month=a)
            queryset = queryset.filter(condition)
            print (queryset)
    if year:
        if year != 'all':
            for a in year:
                condition |= Q(created_at__year=a)
            queryset = queryset.filter(condition)
            print (queryset)
            
        
    return queryset

当我按年份过滤时,它返回 200 个响应,但返回 0 个对象

当我按月过滤时,我什至得不到 200 响应,它返回 500 响应

1 个答案:

答案 0 :(得分:1)

docs 中所述,getlist 返回一个列表(在您的情况下,url 中提供的所有月份或年份)。

您可以使用 __in 按值列表过滤。

考虑到这一点,你可以试试这个:

class FinalListView(generics.ListAPIView):
    serializer_class = FinalSerializer
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]

    def get_queryset(self):
        queryset = Final.objects.all()
        months = self.request.query_params.getlist('month')
        years = self.request.query_params.getlist('year')

        if months and 'all' not in months:
            queryset = queryset.filter(created_at__month__in=months)
            print (queryset)
        if years and 'all' not in years:
            queryset = queryset.filter(created_at__year__in=years)
            print (queryset)

    return queryset

像这样发送请求:GET /final/?month=1, GET /final/?year=2020, ...

相关问题