繁体   English   中英

Django Rest 框架: append 值到 ListAPIView

[英]Django Rest Framework: append value to ListAPIView

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,)

这给了我以下 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
    }
    ]
    }   

我还想汇总总平均价格并将其添加到 output,例如:

    {
  "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 object 中都有 total_average_price。 我还尝试覆盖 ListAPIView (获取函数),但这杀死了内置分页:(

我希望有人能够帮助我找到解决这个问题的巧妙方法。

您可以创建自定义分页 class 并覆盖其get_paginated_response 在分页.py 中:

class PricesPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page'

    def get_paginated_response(self, data):
        prices = [dict(item)['average_price'] for item in data]
        page_price_avg = sum(prices)/ len(prices)
        return Response({
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'count': self.page.paginator.count,
            'page_price_avg': page_price_avg,
            'results': data,
        })

在 views.py 中,设置您的自定义分页:

class PriceTrendListView(ListAPIView):
    pagination_class = PricesPagination
    serializer_class = PriceTrendSerializer
    queryset = Car.objects.all()

然后,您将能够看到每个页面的平均价格。

from rest_framework import pagination
from rest_framework.response import Response


class CustomPagination(pagination.PageNumberPagination):
    def get_paginated_response(self, data):
        return Response({
            'count': self.page.paginator.count,
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'total_average_price': 125000,
            'results': data,
        })


class Pricetrend(generics.ListAPIView):
    queryset = Cars.objects.annotate(...)
    serializer_class = PricetrendSerializer
    pagination_class = CustomPagination

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM