在Django REST框架的API根目录中包含list_route方法

时间:2015-05-05 17:44:47

标签: python django rest url-routing

我正在使用Django REST框架,并且我有一个带有额外列表路由方法的视图集。如何在API根页中包含该方法的URL?

以下是我的视图集的简化版本:

class BookViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = (permissions.IsAuthenticated, )

    @list_route(methods=['get'])
    def featured(self, request):
        queryset = self.filter_queryset(self.get_queryset()).filter(featured=True)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

我在urls.py注册了视图集:

router = DefaultRouter()
router.register('books', BookViewSet)
urlpatterns = patterns(
    url(r'^api/', include(router.urls), name='api_home'),
    #...
    )

books/featured的网址路由正确,但当我转到http://localhost:8000/api时,我只看到这个:

HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, HEAD, OPTIONS

{
    "books": "http://localhost:8000/api/books/"
}

如何为此类内容添加条目?

"book-featured-list": "http://localhost:8000/api/books/featured"

4 个答案:

答案 0 :(得分:2)

您可以尝试从负责api根视图的DefaultRouter继承并重新定义get_api_root_view方法。

class MyRouter(routers.DefaultRouter):
    def get_api_root_view(self):
        """
        Return a view to use as the API root.
        """
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        class APIRoot(views.APIView):
            _ignore_model_permissions = True

            def get(self, request, *args, **kwargs):
                ret = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in api_root_dict.items():
                    if namespace:
                        url_name = namespace + ':' + url_name
                    try:
                        ret[key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        # Don't bail out if eg. no list routes exist, only detail routes.
                        continue

                ret['book-featured-list'] = '%s%s' % (ret['books'], 'featured/')

                return Response(ret)

        return APIRoot.as_view()

P.S。对不起,在我发布答案之前没看到你的评论

答案 1 :(得分:2)

您可以安装软件包django-rest-swagger,只需点击此处:https://github.com/marcgibbons/django-rest-swagger

它比DRF的api列表页面更强大。它将为您的模块列出所有其余的api(包括list_route / detail_route apis),您还可以在页面上进行一些api测试(CRUD)。

答案 2 :(得分:0)

我根据Likeon的回答使用此解决方案:

class MyRouter(routers.DefaultRouter):
    def get_api_root_view(self, api_urls=None):
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        api_root_dict['books/featured'] = 'book-featured'

        return self.APIRootView.as_view(api_root_dict=api_root_dict)

答案 3 :(得分:-1)

你可以试试,把它放在你的urlpatterns下面。 你的网址将是这样的:

http://localhost:8000/api/books/

from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = format_suffix_patterns(urlpatterns)