i have been trying to get the response as given below but am a little stuck as to how to achieve it.. I tried other ways without serializers but then my pagination does not work as expected..
the question for the pagination issue is Pagination does not seem to be working using get method and APIView
below is my dataset:
data = [['1','2023-01-04 12:39','{"kpiThreshold": 23, "kpiValue": 25, "kpiDiff": 2}'],
['2','2023-01-03 12:39','{"kpiThreshold": 23, "kpiValue": 26, "kpiDiff": 3}'],
['1','2023-01-02 12:39','{"kpiThreshold": 23, "kpiValue": 27, "kpiDiff": 4}']]
df_new = pd.DataFrame(data, columns=['id', 'date','kpi'])
df_new
serializer.py
from rest_framework import serializers
from pegaapi.models import PegaAlerts
class AlertsSerializer(serializers.ModelSerializer):
class Meta:
model = PegaAlerts
fields = ('id','generateddatetime','kpiValues')
views.py
class FullLogsAPI(GenericAPIView):
pagination_class=CustomPagination
serializer_class = AlertsSerializer
def get(self,request, *args, **kwargs):
envid = self.kwargs.get('envid')
nodeid = self.kwargs.get('nodeid')
startdatetime = self.request.GET.get('startdatetime')
enddatetime = self.request.GET.get('enddatetime')
filter_list=PegaAlerts.objects.filter(envId=envid, serverId=nodeid, generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime')
page = self.paginate_queryset(filter_list)
serializer = AlertsSerializer(page, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
Response :
[
{
"id": 1,
"generateddatetime": "2023-01-04 12:39",
"kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 25, \"kpiDiff\": 2}"
},
{
"id": 2,
"generateddatetime": "2023-01-03 12:39",
"kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 26, \"kpiDiff\": 3}"
},
{
"id": 3,
"generateddatetime": "2023-01-02 12:39",
"kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 27, \"kpiDiff\": 4}"
}
]
But the response i'm looking for is
[
{
"id": 1,
"generateddatetime": "2023-01-04 12:39",
"kpiValues": {
"kpiThreshold": 23,
"kpiValue": 25,
"kpiDiff": 2
}
},
{
"id": 2,
"generateddatetime": "2023-01-03 12:39",
"kpiValues": {
"kpiThreshold": 23,
"kpiValue": 26,
"kpiDiff": 3
}
},
{
"id": 3,
"generateddatetime": "2023-01-02 12:39",
"kpiValues": {
"kpiThreshold": 23,
"kpiValue": 27,
"kpiDiff": 4
}
}
]
Any pointers or suggestions how i can achieve the same ?
CodePudding user response:
You can update your serializer and try this,
from rest_framework import serializers
from pegaapi.models import PegaAlerts
import json
class AlertsSerializer(serializers.ModelSerializer):
kpiValues = serializers.SerializerMethodField()
def get_kpiValues(self, obj):
return json.loads(obj.kpiValues)
class Meta:
model = PegaAlerts
fields = ('id','generateddatetime','kpiValues')