【问题标题】:Using Django Rest Framework, is it possible to get results internally on server within Django?使用 Django Rest Framework,是否可以在 Django 内部的服务器上获取结果?
【发布时间】:2017-08-23 12:19:03
【问题描述】:

我有一个复杂的 DRF ViewSet,它支持以网格视图为后端的分页、过滤、排序等。要构建“导出”功能,我需要能够采用与我的端点使用相同的查询字符串,例如:

?obj_id=129&ordering=latitude&city__icontains=nap

并且能够在 Django 中以某种方式将该字符串发送到 DRF 并在应用所有视图的过滤器、排序等之后获得完全修改的 queryset(与 GET 相同)。我可以使用完全渲染的 json 响应或一些临时过滤器应用的查询集。这种方式可以使用DRF吗?

【问题讨论】:

    标签: django django-rest-framework django-orm


    【解决方案1】:

    您应该为您的视图集编写一个 CSV 渲染器并获取该内容类型以导出 CSV。 甚至one 已经可用。

    【讨论】:

      【解决方案2】:

      是的,如果您已经有一个 request 对象,即如果您想将此 DRF 视图集用于另一个具有请求对象的视图:

      def another_view(request):
      
          # make a copy of the `GET` attribute of request object
          request.GET = request.GET.copy()
      
          # now you can set the query params on this GET object
          # ?obj_id=129&ordering=latitude&city__icontains=nap
          request.GET['obj_id'] = 129
          request.GET['ordering'] = 'latitude'
          request.GET['city__icontains'] = 'nap'
      
          # you can also set paging options in similar way
      
          # now instantiate the viewset
          vs = DRFViewset.as_view()
      
          # call the view for response
          # set kwargs as you need
          response = vs(request, *args, **kwargs)
      
          # response.data will have what you want here
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-03
        • 2018-10-19
        • 1970-01-01
        • 1970-01-01
        • 2016-03-20
        相关资源
        最近更新 更多