从过滤器中的视图更改查询集

change the queryset from a view in a filter

我想要默认行为,其中视图 returns 中的查询集记录 publish_at 日期小于某个日期。我还想要布尔 DRF 过滤器,如果设置为 true returns 所有记录,无论 publish_at 日期是什么。

views.py:

    queryset = ProjectNews.objects.exclude(publish_at__gte=timezone.now())

filters.py:

    from django_filters import rest_framework as filters
    class ProjectNewsFilterSet(filters.FilterSet):
        not_published = filters.BooleanFilter(
                            method='show_not_published_news'
                        )
        def show_not_published(self, queryset, name, value):
            if value:
                # queryset based on queryset from view
                # does not return all the records
                return queryset.all() 
            return queryset.exclude(publish_at__gte=timezone.now())

只需将查询集更改为:

queryset = ProjectNews.objects.all()

比你在过滤器中过滤查询集。