[英]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_context_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.