Home > front end >  I am getting only one object in post method inside APIView of django rest framework even if I used S
I am getting only one object in post method inside APIView of django rest framework even if I used S

Time:11-18

##Any one knows how to fix this. I am getting only one object in post method inside APIView of django rest framework even if I used ScrapyItem.objects.all(). Anyone knows why##

class ScrapyViewSet(APIView):
        def get(self, request, format=None):
            snippets = ScrapyItem.objects.all()
            serializer =ScrapySerializer(snippets, many=True)
            return Response(serializer.data)
    
    
        def post(self, request):
            snippets = ScrapyItem.objects.all()
            domain=request.data['domain']
            print(domain)
            
            
            for i in snippets:
                print(i)
                if i.domain==domain:
                    return Response({"status": "success", "data": str(i.data)}, status=status.HTTP_200_OK) 
    
                else:
                    return Response({"status": "error", "data": 'error'}, status=status.HTTP_400_BAD_REQUEST)

CodePudding user response:

A return statement stops the function and returns the result of the expression after the return keyword. This thus means that even if there are other objects with the given domain, these will not be considered.

You can simply serialize the collection of items that match with the given domain with:

class ScrapyViewSet(APIView):
    def get(self, request, format=None):
        snippets = ScrapyItem.objects.all()
        serializer =ScrapySerializer(snippets, many=True)
        return Response(serializer.data)
    
    def post(self, request):
        domain=request.data['domain']
        snippets = ScrapyItem.objects.filter(domain=domain)
        if snippets:
            serializer = ScrapySerializer(snippets, many=True)
            return Response({'status': 'success', 'data': serializer.data}, status=status.HTTP_200_OK) 
        else:
            return Response({'status': 'error', 'data': 'error'}, status=status.HTTP_400_BAD_REQUEST)

Normally a POST request is however used to update the state of the application: create, update, or remove entities, not retrieve items.

  • Related