我正在使用ListAPIView,但我无法过滤结果。 我的代码是: 在这种情况下, lookup_field被忽略,但是文档说它也支持这个类。 如果我试图实现一个自定义get了一个通用的观点,我不知道如何重新实现paginate_by 。 有任何想法吗? ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
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(获取函数),但这杀死了内置分页:(
我希望有人能够帮助我找到解决这个问题的巧妙方法。
您可以创建自定义分页类并覆盖其get_paginated_response
。 在 paginations.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.