StackOverflow community,
I've got the following serializer and view:
serializers.py
class PricetrendSerializer(serializers.ModelSerializer):
timestamp = serializers.DateTimeField()
average_price = serializers.IntegerField()
class Meta:
model = Cars
fields = ('timestamp', 'average_price')
views.py
class Pricetrend(generics.ListAPIView):
queryset = Cars.objects.annotate(timestamp=TruncMonth('timestamp')).values('timestamp').annotate(average_price=Avg('price'))
serializer_class = PricetrendSerializer
filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilter)
filterset_class = PriceFilter
search_fields = ['description']
ordering_fields = ['timestamp', 'average_price']
ordering = ['timestamp']
permission_classes = (permissions.IsAuthenticated,)
Which is giving me the following output:
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"timestamp": "2020-04-01T00:00:00",
"average_price": 90274
},
{
"timestamp": "2020-05-01T00:00:00",
"average_price": 99253
}
]
}
I would like to also aggregate the total average price and add it to the output, e.g.:
{
"count": 2,
"next": null,
"previous": null,
"total_average_price": 125000,
"results": [
{
"timestamp": "2020-04-01T00:00:00",
"average_price": 90274
},
{
"timestamp": "2020-05-01T00:00:00",
"average_price": 99253
}
]
}
Unfortunately, I do not know how this could be done as adding it to the serializer will result in having the total_average_price in every JSON object. I also tried to override the ListAPIView (get function) but this killed the built-in pagination :(
I hope that somebody is able to help me find a neat way to solve this.
question from:
https://stackoverflow.com/questions/65891271/django-rest-framework-append-value-to-listapiview 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…