Home > Mobile >  Access Json object name
Access Json object name

Time:02-11

I want to get data with request.data.columns in frontend.I can do it with ViewSet with list method but how to do it with generics.APIView. Below is my viewsets and generics code:

class TestList(viewsets.ViewSet):
     queryset = Test.objects.all()
     def list(self,request):
         serializer = TestSerializer(self.queryset, many = True)
         return Response({'columns': serializer.data})

class TestList(generics.RetriveAPIView):
    queryset = Test.objects.all()
    serializer_class = TestSerializer

CodePudding user response:

class TestList(APIView):
     queryset = Test.objects.all()
     def list(self,request):
         serializer = TestSerializer(self.queryset, many = True)
         return Response({'columns': serializer.data})

change your urls.py like this.

path(r"url", TestList.as_view({"get": "list"}))

CodePudding user response:

Correct code:

class TestList(APIView):
     queryset = Test.objects.all()
     def list(self,request):
         queryset = self.get_queryset()
         serializer = TestSerializer(queryset, many = True)
         return Response({'columns': serializer.data})

Details about why i had to add queryset = self.get_queryset() instead of directly access self.queryset.From official drf documentation:

queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.

  • Related