为什么django-filter不能按预期工作

问题描述 投票:0回答:1

我有以下基于类的视图的views.py文件。

from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .permissions import IsOwner, IsNotBlacklistedUser
from rest_framework import filters
from django_filters import rest_framework as filters_django

from core.models import Book
from .serializers import BookSerializer, AllBookSerializer


class BookApiView(APIView):
    authentication_classes = (JSONWebTokenAuthentication, )
    permission_classes = (IsAuthenticated, IsNotBlacklistedUser)
    filter_backends = (filters_django.DjangoFilterBackend,)
    filterset_fields = ('title',)

    def get(self, request):
        books = Book.objects.filter(
            user=request.user.id, is_published=True).order_by('-title')
        serializer = BookSerializer(books, many=True)
        return Response(serializer.data)

    def post(get, request):
        data = request.data
        serializer = BookSerializer(data=data)
        if serializer.is_valid():
            serializer.save(user=request.user)
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

当我在django rest框架UI中加载此视图时,我看不到任何过滤器选项。我不确定该怎么做。有人可以指出我可能需要做些什么才能使它正常工作。我还已经将'django_filters'添加到我的settings.py文件中。

提前感谢。

django-rest-framework django-filter
1个回答
0
投票

您可以使用ViewSet。

class BookApiViewSet(CreateModelMixin, ListModelMixin, GenericViewSet):
    authentication_classes = (JSONWebTokenAuthentication, )
    permission_classes = (IsAuthenticated, IsNotBlacklistedUser)
    filter_backends = (filters_django.DjangoFilterBackend,)
    filter_fields = ('title',)

或通用APIViews

class BookApiViewSet(generics.ListCreateAPIView):
     authentication_classes = (JSONWebTokenAuthentication, )
     permission_classes = (IsAuthenticated, IsNotBlacklistedUser)
     filter_backends = (filters_django.DjangoFilterBackend,)
     filter_fields = ('title',)

或者您可以扩展GenericAPIView并手动编写过滤器。

class BookApiViewSet(GenericAPIView):
     authentication_classes = (JSONWebTokenAuthentication, )
     permission_classes = (IsAuthenticated, IsNotBlacklistedUser)
     filter_backends = (filters_django.DjangoFilterBackend,)
     filter_fields = ('title',)
     queryset = self.filter_queryset(self.get_queryset())

     def get(self, request, *args, **kwargs):
         page = self.paginate_queryset(queryset)
         if page is not None:
             serializer = self.get_serializer(page, many=True)
             return self.get_paginated_response(serializer.data)

         serializer = self.get_serializer(queryset, many=True)
         return Response(serializer.data)

注意:我没有测试代码,您可能需要稍作调整。

© www.soinside.com 2019 - 2024. All rights reserved.