gpt4 book ai didi

python - 在 Django REST 框架 API 根中包含 list_route 方法

转载 作者:太空狗 更新时间:2023-10-29 19:27:41 25 4
gpt4 key购买 nike

我正在使用 Django REST 框架,并且我有一个带有额外列表路由方法的 View 集。我怎样才能让该方法的 URL 包含在 API 根页面中?

这是我的 View 集的简化版本:

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 中注册 View 集:

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

books/featured 的 URL 路由正确,但是当我转到 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"

最佳答案

可以尝试继承负责api Root View 的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()

附言抱歉,在我发布答案之前没有看到您的评论

关于python - 在 Django REST 框架 API 根中包含 list_route 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30059795/

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