Django Restframework:用于查询集统计摘要的视图? [英] Django Restframework: What view to use for statistical summary of queryset?
问题描述
Django Restframework为查询集的列表和单个模型提供通用视图.哪种视图类最适合创建提供查询集统计摘要的终结点?
Django Restframework provides generic views for lists and single models from querysets. Which view class would be most appropriate for creating an endpoint that serves a statistical summary of a queryset?
我当然可以从头开始构建APIView,但是我想重用ListAPIView上的大多数设置(例如get_queryset,permission_classes等)以及url参数.
I could surely build an APIView from scratch but I would like to reuse most of the settings on the ListAPIView (such as get_queryset, permission_classes, etc.) as well as url parameters.
端点的组织方式如下:
/api/data/ # data endpoint
/api/data/summary/ # summary endpoint
摘要端点将提供与单个模型实例无关的单个对象.
The summary endpoint will provide a single object that is not related to a single model instance.
感谢您提供最佳实践建议.
Thank you for any best practice advice.
推荐答案
现在,我提出了以下解决方案:
For now I came up with following solution:
# pseudo-code !
class DataView(ListAPIView):
"""Returns a queryset as a serialized and paginated list.
Set queryset, permissions, etc. here."""
def get_queryset(self):
# add complex lookup here
queryset = self.queryset
return queryset
class SummaryView(DataView):
"""Overwrite the get method to serve different
content, e.g. statistical summary."""
def summarize(self, request, *args, **kwargs):
"""This can be moved to a Mixin class."""
# make sure the filters of the parent class get applied
queryset = self.filter_queryset(self.get_queryset())
# do statistics here, e.g.
stats = {'count': queryset.count()}
# not using a serializer here since it is already a
# form of serialization
return Response(stats)
def get(self, request, *args, **kwargs):
return self.summarize(request, *args, **kwargs)
这篇关于Django Restframework:用于查询集统计摘要的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!