1

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

@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' 类型的对象的 TypeError 没有 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中编写正确的视图

4

1 回答 1

0

many=True从中删除serializer_class。如下创建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 类继承 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

于 2020-08-03T16:28:38.067 回答