有没有办法为@list_route
使用过滤器,就像在DRF中使用它们的根ViewSet一样?
我有一个模型,我已配置过滤器和详细路线,我不能:
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
?
答案 0 :(得分:7)
您应该在使用@list_route:
修饰的方法中调用filter_queryset
@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
也是个好主意。