是否可以通过APIVIEW在djangorestframework中创建两个GET端点

时间:2018-02-14 14:12:29

标签: django-rest-framework

我需要在一个类中的django rest框架中创建两个GET端点 这是端点将通过api

与另一个系统一起使用

我试过

class MyApiView(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        return Response({'test':'test'})

    @list_route(methods=['GET'], )
    def two_endpoint(self, request):
        return Response({'test': 'test'}) 

但这不起作用 提前谢谢

1 个答案:

答案 0 :(得分:1)

尝试使用ModelViewset class

views.py

<击>
from rest_framework import viewsets


class MyApiView(viewsets.ModelViewSet):
    permission_classes = (AllowAny,)
    serializer_class = MySerializer
    queryset = Sample.objects.all()

    def function_name_1(self, request):
        # do stuff
        return Response(data="return your data")

    def function_name_2(self, request):
        # do stuff
        return Response(data="return your data")

    def function_name_3(self, request, pk):
        # do stuff
        return Response(data="return your data")

<击>
urls.py

from rest_framework.routers import DefaultRouter
from django.conf.urls import url
router = DefaultRouter()
router.register(r'myendpoint', MyApiView)

urlpatterns = [
url(r'^myendpoint/end_point_1/$', MyApiView.as_view({'get': 'function_name_1'}), name='function_name_1'),
url(r'^myendpoint/end_point_2/$', MyApiView.as_view({'post': 'function_name_2'}), name='function_name_2'),
url(r'^myendpoint/end_point_3/$', MyApiView.as_view({'put': 'function_name_3'}), name='function_name_3'),
              ]+router.urls


UPDATE-1
将您的views.py更改为此,

from rest_framework import viewsets


class MyApiView(viewsets.ViewSet):
    permission_classes = (AllowAny,)

    def function_name_1(self, request):
        # do stuff
        return Response(data="return your data")

    def function_name_2(self, request):
        # do stuff
        return Response(data="return your data")

    def function_name_3(self, request):
        # do stuff
        return Response(data="return your data")