If i had a model as below, how would i return the total number of miles in the DB? If i use the aggregate function then it will work, but it will iterate through all objects and give me the total next to those objects.
models.py
from django.db import models
class Rec(models.Model):
name = models.CharField(max_length=50)
miles = models.IntegerField()
serializers.py
class SummarySerializer(serializers.Serializer):
total_miles = serializers.SerializerMethodField()
def get_total_miles(self, obj):
return Rec.objects.filter(name=obj.name).aggregate(Sum('miles'))
views.py
class SummaryViewSet(viewsets.ModelViewSet):
serializer_class = SummarySerializer
queryset = Rec.objects.all()
current output
[{'total':1000, 'total':1000, 'total':1000.... etc}]
Desired output (one instance of the value)
[{'total_miles': 1000}]