0

I would like to have default behaviour where queryset in a view returns records where publish_at date is less than some date. I also want to have boolean DRF filter that if set to true returns all the records no matter what publish_at date is.

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())
Blaze
  • 79
  • 6

1 Answers1

1

Just change queryset to:

queryset = ProjectNews.objects.all()

Than you filter queryset in your filter.

Yura Bysaha
  • 721
  • 6
  • 17
  • Yes, you are right. It is simpler than I thought. The only problem I have with this solution is how to get the Project ID. I did it using value from the request but I don't know if it is the right way?: ProjectNews.objects.filter( project=self.request.parser_context['kwargs']['parent_lookup_project']) – Blaze Nov 12 '19 at 12:11
  • Could you show your view, I think you have Id there – Yura Bysaha Nov 13 '19 at 12:58