0

HI Everyone i am creating api using drf but i want response with different formet, below i have mention my current response and expected response.how can achieve me my expected api response formet.

views.py

class TeamlistViewset(viewsets.ViewSet):
    def list (self,request):
        team=Team.objects.all()
        serializer=TeamSerializer(team,many=True)
        return Response(serializer.data)

api response

[
    {
        "id": 1,
        "name": "Deadly Shark"
    }
]

expected api response

{
    "message": "list retrieval",
    "error": false,
    "code": 200,
    "results": {
        "totalItems": 1,
        "pageData": [
            {
                "id": 1,
                "name": "Deadly Shark"
                
            }
        ],
        "totalPages": null,
        "currentPage": 0
    }
}

2 Answers 2

2

this is solution

class DriverlistViewset(viewsets.ViewSet):
    # permission_classes = (IsAuthenticated,)

    def list (self,request):
        team=Team.objects.all()
        serializer=TeamSerializer(team,many=True)
        # headers=self.get_success_headers(serializer.data)
        try:
            return Response({'message':'sucess','error':False,'code':200,'result':{'totalItems':len(serializer.data),'items':serializer.data,'totalPages':'null','currentPage':0}},status=HTTP_200_OK)
        except Exception as e:
            return Response({'message':'fail','error':True,'code':500,'result':{'totalItems':0,'items':[],'totalPages':0,'currentPage':0}})
Sign up to request clarification or add additional context in comments.

1 Comment

Is this a solution for your question, or a clarification? If it's a solution, please edit the answer to say so, if it's a clarification, please edit it into the question.
0

A bit late but you can do it like this

class TeamlistViewset(viewsets.ViewSet):
    def list (self,request):
        team=Team.objects.all()
        serializer=TeamSerializer(team,many=True)
        response = {
           "message": "list retrieval",
           "error": False,
           "code": 200,
           "results": serializer.data
        }
        return Response(response, status=status.HTTP_200_OK)

If you get type error that you cannot send data of Type Team i.e. your model, then serialize the data you receive first. Also it is better to add status code besides the response such as in the last line of the above code and not inside the response dictionary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.