我是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_context_data(self, **kwargs):
context = super(CategoryList, self).get_context_data(**kwargs)
context['category'] = my_category
return context
使用APIView类与使用常规视图类几乎相同,像往常一样,传入的请求被分派到适当的处理程序方法,如.get()
或.post()
Docs
通过重写get
方法,您可以从URL中检索段塞并使用它来获取类别对象。
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()),