Django Restframework为查询集中的列表和单个模型提供通用视图。哪个视图类最适合创建提供查询集统计摘要的端点?
我可以从头开始构建一个APIView,但我想重用ListAPIView上的大多数设置(例如get_queryset,permission_classes等)以及url参数。
端点的组织方式如下:
/api/data/ # data endpoint
/api/data/summary/ # summary endpoint
摘要端点将提供与单个模型实例无关的单个对象。
感谢您提供最佳实践建议。
答案 0 :(得分:0)
现在我想出了以下解决方案:
# 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)