2017-03-08 35 views
3

有沒有一種方法可以像在DRF中將ViewSet使用過濾器一樣使用@list_route的過濾器?在drf中使用帶有list_routes的過濾器

我有我爲配置過濾器的模型和詳細路線,我不能:

class ListingViewSet(viewsets.ModelViewSet): 
    # disable listing after 5 flags 
    queryset = Listing.objects.all() 

    serializer_class = ListingSerializer 
    filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter) 
    permission_classes = (ListingOwnerCanEdit,) 
    filter_class = ListingFilter 

    @list_route() 
    def homepage(self, request): 
     queryset = Listing.objects.filter(flags__lt=5, closed=False) 

     ### Doesn't work 
     # filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter) 
     # permission_classes = (ListingOwnerCanEdit,) 
     # filter_class = ListingFilter 
     # ordering_filter = OrderingFilter() 
     # ordering_fields = ('price', 'views') 
     # search_fields = ('title', 'description') 

     serializer = ListingSerializer(queryset, many=True, context=self.get_serializer_context()) 
     return Response(serializer.data) 

而且ListingFilter是:

class ListingFilter(django_filters.rest_framework.FilterSet): 
    min_price = django_filters.NumberFilter(name="price", lookup_expr='gte') 
    max_price = django_filters.NumberFilter(name="price", lookup_expr='lte') 
    author_pk = django_filters.CharFilter(name='author_pk') 

    class Meta: 
     model = Listing 
     fields = ['price_type', 'sale_type', 'category__name', 'min_price', 'max_price', 'description', 'title', 
       'listing_date', 'views', 'number_of_inquiries', 'author_pk', 'closed', 'closing_date'] 

是否有使用ListingFilter與網頁的方式列出路線?

回答

6

你應該叫filter_queryset在你的方法飾@list_route:

@list_route() 
def homepage(self, request): 
    queryset = self.get_queryset().filter(flags__lt=5, closed=False) 
    queryset = self.filter_queryset(queryset) 

    serializer = ListingSerializer(queryset, many=True, context=self.get_serializer_context()) 
    return Response(serializer.data) 

編輯:也就是用self.get_queryset()而不是Listing.objects一個好主意。

相關問題