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