gpt4 book ai didi

django - 向路由器或 View 集添加更多 View (Django-Rest-Framework)

转载 作者:行者123 更新时间:2023-12-03 11:07:50 25 4
gpt4 key购买 nike

从本质上讲,我试图找到一种在不创建自定义路由器的情况下将更多 View 附加到路由器的好方法。 有什么好方法可以实现这一点?

这有点类似于我想要完成的事情。为了这个问题,变量名称已更改,并且我要介绍的示例方法非常简化。

路由器:

router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls

View 集
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()

我需要包括的另一种方法类型的一个示例。 (有很多这样的):
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)

最终结果是以下 URL 将正常工作并“干净地”实现。
GET example.com/myobjects/123/locations

最佳答案

answer given by mariodev以上是正确的,只要您只想制作 GET要求。

如果您想 POST对于要附加到 ViewSet 的函数,您需要使用 action装饰器:

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/
http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing如果您有兴趣,可以提供更多信息!

关于django - 向路由器或 View 集添加更多 View (Django-Rest-Framework),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18969798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com