环境:django == 1.11.11,rest_framework
具有相同名称的方法可以使用装饰器在同一视图类或视图集中处理不同的路由吗?
示例:
class Indexs(APIView):
@decorator("detailed/")
def get(self, request):
pass
@decorator("list/")
def get(self, request):
pass
#个补充
我想在同一个视图类中处理两个GET请求。一个GET请求详细信息,另一个请求列出内容,但同名请求被覆盖
urls.py
from django.conf.urls import url
from indexs import views
urlpatterns = [
# url(r'category/$', views.Indexs.as_view()),
url(r'list/$', views.Indexs.as_view()),
url(r'detailed/$', views.Indexs.as_view()),
]
views.py
class Indexs(APIView):
def get(self, request):
return Response({"list": "list"})
def get(self, request):
return Response({"detailed": "detailed"})
http://127.0.0.1/list和http://127.0.0.1/detailed 返回结果都是
{
"detailed": "detailed"
}
但是我想要
{
"list": "list"
}
{
"detailed": "detailed"
}
答案 0 :(得分:0)
了解有关在django rest framewrok documentation中实现基于类的视图的更多信息,这非常简单。 Django Rest Framework使使用内置的通用视图轻松编写DRY代码。
例如,下面的ListCreateAPIView
之类的内置generic view将执行GET
和POST
Http方法。
您可以从网址中获取摘要列表和摘要列表:
urls.py
urlpatterns = [
url(r'^snippets/$', views.SnippetList.as_view()),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
]
views.py
class SnippetAPIView(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer