将更多视图添加到路由器或视图(Django-Rest-Framework) [英] Adding more views to a Router or viewset (Django-Rest-Framework)
问题描述
基本上,我试图找到一个很好的方式来附加更多的视图到路由器,而不创建自定义路由器。 这是一个很好的方法来实现这一点?
Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. What's a good way to accomplish this?
这是一些与我要完成的工作相当的东西。变量名称已经更改,为了这个问题,我想介绍的示例方法极其简化。
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
路由器:
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
ViewSet
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
我需要包括的另一种方法类型的一个例子。 (其中有很多):
One example of another method type I need to include. (There are many of these):
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
最终结果是,以下URL可以正常工作并被干净地实现。
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
GET example.com/myobjects/123/locations
推荐答案
由mariodev给出的答案是正确的,只要你只想使 GET
请求。
The answer given by mariodev above is correct, as long as you're only looking to make GET
requests.
如果要将 POST
添加到要附加到的ViewSet,您需要从rest_framework中使用操作
装饰器:
If you want to POST
to a function you're appending to a ViewSet, you need to use the action
decorator:
from rest_framework.decorators import action, link
from rest_framework.response import Response
class MyObjectsViewSet(viewsets.ViewSet):
# For GET Requests
@link()
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
# For POST Requests
@action()
def update_location(self, request, pk):
""" Updates the object identified by the pk """
location = self.get_object()
location.field = update_location_field() # your custom code
location.save()
# ...create a serializer and return with updated data...
然后你将 POST
到一个格式如下的URL:
/ myobjects / 123 / update_location /
Then you would POST
to a URL formatted like:
/myobjects/123/update_location/
这篇关于将更多视图添加到路由器或视图(Django-Rest-Framework)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!