1π
β
A Django query can be used in the backend to perform aggregation; new model is not needed for summary data.
An SQL query for getting average age by gender from a βpersonβ table would be something like this.
SELECT gender, AVG(age) AS average_age
FROM person
GROUP BY gender;
The equivalent Django query would be similar to this.
from django.db.models import Avg
result = Person.objects.values('gender')
.annotate(average_age=Avg('age'))
UPDATE: Adding a class based API view
class GetData(APIView):
def get(self):
result = Test.objects.values('gender').annotate(average_age=Avg('age'))
response_data = {}
response_data['data'] = list(result)
return Response(response_data, status=status.HTTP_200_OK)
urls.py should be updated to use this API view.
path('getdata/', GetData.as_view()),
π€krskara
Source:stackexchange.com