简体   繁体   中英

django rest framework Convert a view to api

I am a beginner in drf and I need to create this view in drf, but I don't know what method I should use.

‍‍‍‍‍‍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
‍

Using the APIView class is pretty much the same as using a regular View class, as usual, the incoming request is dispatched to an appropriate handler method such as .get() or .post() Docs

By overriding the get method, you can retrieve the slug from the URL and use it to get the category 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)

And the URL would look something like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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