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

Viewed 152

I have 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": [ { ... }, { ... } ] }

Expected result should be { "status": "success", "data": [ { ... }, { ... } ] }

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)

Many thanks in advance, efends

1 Answers

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

Related