I'm using Django to feed a front end web page built with React.
I have an API that gets the necessary data with some formatting, but it's pretty slow. Any suggestions on how to build a faster API? It's currently returning 8 records which takes >3 seconds.
def deployed_data(request):
deployments = deployment.objects.filter(LAUNCH_DATE__isnull=False).filter(HISTORICAL=False)
res = []
for dep in deployments:
crt_dep = {
"FLOAT_SERIAL_NO":dep.FLOAT_SERIAL_NO,
"PLATFORM_NUMBER":dep.PLATFORM_NUMBER,
"PLATFORM_TYPE":dep.PLATFORM_TYPE.VALUE,
"DEPLOYMENT_CRUISE_ID":dep.DEPLOYMENT_CRUISE_ID,
"DEPLOYMENT_PLATFORM":dep.DEPLOYMENT_PLATFORM.VALUE,
"LAUNCH_DATE":dep.LAUNCH_DATE.strftime("%Y-%m-%d"),
"status":dep.status,
"last_report":dep.last_report.strftime("%Y-%m-%d %H:%M"),
"next_report":dep.next_report.strftime("%Y-%m-%d %H:%M"),
"days_since_last":dep.days_since_last,
"last_cycle":dep.last_cycle,
"age":dep.age.days
}
res.append(crt_dep)
return JsonResponse(res, status = 200, safe=False)
CodePudding user response:
of course it's slower, you reialize on every loop every value in the dict is a separate hit to the database! just use drf serializer or even django serializer to convert these data at once or use values after filter
CodePudding user response:
views.py
class GetDeploymentData(generics.ListAPIView):
serializer_class = DeployedDataSerializer
queryset=deployment.objects.filter(LAUNCH_DATE__isnull=False).filter(HISTORICAL=False)
serializers.py
class DeployedDataSerializer(serializers.Serializer):
FLOAT_SERIAL_NO = serializers.IntegerField()
PLATFORM_NUMBER = serializers.IntegerField()
PLATFORM_TYPE = serializers.CharField()
status = serializers.CharField()
DEPLOYMENT_CRUISE_ID = serializers.CharField()
DEPLOYMENT_PLATFORM = serializers.CharField()
LAUNCH_DATE = serializers.DateTimeField(format="%Y-%m-%d %H:%M")
last_report = serializers.DateTimeField(format="%Y-%m-%d %H:%M")
next_report = serializers.DateTimeField(format="%Y-%m-%d %H:%M")
days_since_last = serializers.IntegerField()
last_cycle = serializers.IntegerField()
age = serializers.IntegerField(source="age.days")
As Mohamed pointed out, serializers are much faster. But this is still not as fast as the same page created using django's templates.