StackOverflow 社区,
我有以下序列化程序和视图:
序列化程序.py
class PricetrendSerializer(serializers.ModelSerializer):
timestamp = serializers.DateTimeField()
average_price = serializers.IntegerField()
class Meta:
model = Cars
fields = ('timestamp', 'average_price')
视图.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,)
这给了我以下输出:
{
"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
}
]
}
我还想汇总总平均价格并将其添加到输出中,例如:
{
"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
}
]
}
不幸的是,我不知道如何做到这一点,因为将其添加到序列化程序会导致每个 JSON 对象中都有 total_average_price。我还尝试覆盖 ListAPIView (获取函数),但这杀死了内置分页:(
我希望有人能够帮助我找到解决这个问题的巧妙方法。