如何在 generics.ListAPIView 中编写可以在 Django DRF 中的 APIView 中编写的功能

How to write the functionality in generics.ListAPIView which can be written in APIView in Django DRF

我有一个函数基础视图,它从 URL 获取 2 个参数 http://127.0.0.1:8000/api/v1/contest/0b36d92a-51a7-4752-9df1-e5f2733116c1/paintings/

@api_view(['GET',])
@permission_classes([AllowAny])
def Contest_detail_by_id_and_category(request, id, category_name):
 
    if request.method == 'GET':
        
        artcontests = Artwork.objects.filter(artcontest = id,category__name__iexact=category_name)
        serializer = ArtworkSerializer(artcontests, many=True)
        # serializer = ArtworkSerializer(artcontests, many=True)
        return Response(serializer.data)

给出了正确的结果,但是当我尝试在 generics.ListAPIView 中编写相同的功能时,它给出了

/api/v1/contesty/0b36d92a-51a7-4752-9df1-e5f2733116c1/paintings/ 处出现类型错误 'method' 类型的对象没有 len()

class Contest_detail_by_id_category(generics.ListAPIView):

 
    serializer_class = ArtworkSerializer1(many=True)
    permission_classes = [AllowAny]
    
    def queryset(self):
 
        queryset = Artwork.objects.filter(artcontest = self.kwargs['id'],category__name__iexact=self.kwargs['category_name'])
     
        # queryset = self.get_queryset()
        serializer = ArtworkSerializer1(queryset)
        return Response(serializer.data)

任何人都可以帮助我 - 如何在 generics.ListAPIViewviewsets.ModelViewSet[= 中编写正确的视图14=]

serializer_class 中删除 many=True。如下所示创建 get_queryset 函数,而不是您的 queryset 函数。

class Contest_detail_by_id_category(generics.ListAPIView):

    serializer_class = ArtworkSerializer1
    queryset = Artwork.objects.all()
    permission_classes = [AllowAny]
    
    def get_queryset(self):
        return self.queryset.filter(artcontest = self.kwargs['id'],category__name__iexact=self.kwargs['category_name'])
     

更新:正在工作: ListAPIView class 继承 ListModelMixin.

class ListModelMixin:
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        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)

看这里。 https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py