Efends
Efends

Reputation: 43

How to show the record count together with response data in django-restframework

I have a requirement to show the total record count together with response data in django-restframework. I manage to add the status, but not the total record count as below:

{
  "status": "success",
  "data": [
    {
      ...
    },
    {
      ...
    }
  ]
}

The expected result should be

{
  "status": "success",
  "data": [
    {
      ...
    },
    {
      ...
    }
   ]
}

File views.py

class MyView(APIView):
    serializer_class = MySerializers

    def get(self, request, format=None):
        rs = MyModel.objects.filter(segment_column_name='SEGMENT1')
        serializer = MySerializers(rs, many=True)
        return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)

Upvotes: 2

Views: 570

Answers (1)

ThomasGth
ThomasGth

Reputation: 870

You can just do as follows:

def get(self, request, format=None):
    rs = MyModel.objects.filter(segment_column_name='SEGMENT1')
    serializer = MySerializers(rs, many=True)
    return Response({"status": "success", "data": serializer.data, "count": len(rs)}, status=status.HTTP_200_OK)

FYI: You can also use count() to count the items of your queryset, but in your case len() will be faster

Upvotes: 1

Related Questions