繁体   English   中英

django rest 框架 将视图转换为 api

[英]django rest framework Convert a view to api

我是drf的初学者,我需要在drf中创建这个视图,但我不知道应该使用什么方法。

‍‍‍‍‍‍class CategoryList(ListView):
    template_name = "blog/categorylist.html"
    paginate_by = 10
    def get_queryset(self):
        global my_category
        slug = self.kwargs.get('slug')
        my_category = get_object_or_404(Category, slug=slug)
        return my_category.articles.published()

    def get_conte‍‍‍‍xt_data(self, **kwargs):
        context = super(CategoryList, self).get_context_data(**kwargs)
        context['category'] = my_category
        return context
‍

使用 APIView class 与使用常规视图 class 几乎相同,像往常一样,传入请求被分派到适当的处理程序方法,例如.get().post() Docs

通过覆盖get方法,您可以从 URL 中检索 slug 并使用它来获取类别 object。

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Your other imports

class CategoryListAPIView(APIView):
    def get(self, request, slug):
        category = get_object_or_404(Category, slug=slug)
        articles = category.articles.published()
        return Response(articles, status=status.HTTP_200_OK)

URL 看起来像这样

path('category/<slug:slug>/', CategoryListAPIView.as_view()),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM