无法扩展Django REST Framework视图集来处理多级API

时间:2015-09-14 20:40:30

标签: python django django-rest-framework

我目前正在使用带路由器和视图集的Django REST Framework来处理以下API调用:

/movie/
/movie/highlight
/movie/<id>/other

除了上面的代码之外,我似乎无法找到扩展视图集来处理以下API调用的方法:

/movie/<id>
/movie/<id>/other/<num>

我的views.py目前看起来像这样:

from django.contrib.auth.models import User, Group
from movies.models import Movie


from api.serializers import UserSerializer, GroupSerializer, MovieSerializer

from rest_framework.response import Response
from rest_framework import permissions
from rest_framework import renderers
from rest_framework import viewsets
from rest_framework.decorators import list_route, detail_route

class MovieViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Movie.objects.all().order_by('-title')
    serializer_class = MovieSerializer


    # Handle URL: /movie/highlight
    @list_route(renderer_classes=(renderers.StaticHTMLRenderer,))
    def highlight(self, request, *args, **kwargs):
        print "highlight"
        snippet = "Highlight"
        return Response(snippet)

    # Handle URL: /movie/<id>/other
    @detail_route(renderer_classes=(renderers.StaticHTMLRenderer,))
    def other(self, request, *args, **kwargs):
        print "highlight" + self.kwargs['pk']
        snippet = "Highlight" + self.kwargs['pk']
        return Response(snippet)

我的urls.py看起来像这样:

from django.conf.urls import url, include
from rest_framework import routers
from api import views

router = routers.DefaultRouter()
router.register(r'movie', views.MovieViewSet)		

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

我已经搜索了一些如何执行此操作的示例,包括所有DRF文档,但没有找到任何相关内容。

1 个答案:

答案 0 :(得分:3)

您需要使用此库来拥有嵌套资源 https://github.com/alanjds/drf-nested-routers

使用此库

从我的一个项目中获取示例代码
class NestedChatViewSet(
    viewsets.mixins.CreateModelMixin,
    viewsets.mixins.ListModelMixin,
    viewsets.GenericViewSet):

    queryset = Chat.objects.all()
    serializer_class = ChatSerializer
    permission_classes = (IsAuthenticated, IsUserVerified, IsUserSignedPrivacyAgreement, IsUserOfConsent, )

    def get_queryset(self):
        return Chat.objects.filter(consent=self.kwargs['consent_pk']).order_by('-created')

    def get_consent(self, request, pk=None):
        consent = get_object_or_404(Consent, pk=pk)
        self.check_object_permissions(self.request, consent)
        self.consent = consent
        return self.consent

    def create(self, request, *args, **kwargs):
        self.get_consent(request, pk=kwargs['consent_pk'])
        return super().create(request, *args, **kwargs)

    def perform_create(self, serializer):
        serializer.save(
            user=self.request.user,
            consent=self.consent
        )


    def list(self, request, *args, **kwargs):
        self.get_consent(request, pk=kwargs['consent_pk'])
        return super().list(request, *args, **kwargs)

然后在url.py

router = DefaultRouter()
router.register(r'users', PeopleViewSet)
router.register(r'consents', ConsentViewSet)
consents_router = NestedSimpleRouter(router, r'consents', lookup='consent')
consents_router.register(r'chat', NestedChatViewSet)

现在您可以获得GET,POST同意/ ID /聊天 你可以在这里拥有无限量的嵌套资源。

好的教程就在这里 http://www.machinalis.com/blog/nested-resources-with-django/