从另一个视图调用ViewSet方法 [英] Call ViewSet method from another view

查看:190
本文介绍了从另一个视图调用ViewSet方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Django REST框架API的移动应用程序,并且我调用了许多ModelViewSet来检索数据。我遇到了性能问题,因为用户登录后需要调用很多路由,并且我想保留REST逻辑,但登录后还返回登录响应中所有视图集的内容(保留其过滤器)。

I have a mobile app with a Django REST framework API and I have a lot of ModelViewSet that I call to retrieve data. I have performance issue because I need to call a lot of routes after the user login, and I would like to keep the REST logic but also returns after the login all the viewsets content in the login response (keeping their filters).

是否可以从另一个视图(视图集或APIView)调用ModelViewset list()?

Is it possible to call a ModelViewset list() from another view (viewset or APIView)?

唯一的答案是在SO上发现是做类似的事情

The only answer I found on SO was to do something like this

class ContentGenerator(APIView):

    def get(self, request, format=None):
         data = MyModelViewSet.as_view({'get': 'list'})(request).data

         return Response({'data': data})

但不支持

Exception Value: The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request`

还有其他解决方案吗?

推荐答案

之后一些研究,看起来李由于在其他视图中重用该请求可能会有副作用,因此DRF并未正式支持该请求。这很hacky,但是如果您知道自己在做什么,这是一个解决方案。

After some research, it looks like there might be side-effects to reuse the request in other views, so it is not officially supported by DRF. It is hacky, but if you know what you are doing, this is a solution.

data = MyModelViewSet.as_view({'get': 'list'})(request._request).data

这篇关于从另一个视图调用ViewSet方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆