【问题标题】:Django Restframework: What view to use for statistical summary of queryset?Django Rest Framework:查询集的统计摘要使用什么视图?
【发布时间】:2015-10-26 00:20:21
【问题描述】:

Django Restframework 为来自查询集的列表和单个模型提供通用视图。哪个视图类最适合创建提供查询集统计摘要的端点?

我当然可以从头开始构建 APIView,但我想重用 ListAPIView 上的大部分设置(例如 get_queryset、permission_classes 等)以及 url 参数。

端点的组织方式如下:

/api/data/           # data endpoint
/api/data/summary/   # summary endpoint

摘要端点将提供与单个模型实例无关的单个对象。

感谢您提供任何最佳实践建议。

【问题讨论】:

  • 我认为构建自己的 APIView 类是最好的方法。

标签: python django django-rest-framework


【解决方案1】:

现在我想出了以下解决方案:

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

【讨论】:

  • 我已经按照您的建议完成了。只需自己创建响应。不需要序列化程序。它会使代码过于复杂
猜你喜欢
  • 2016-09-30
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2018-06-17
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多