Skip to content

Commit bdaba48

Browse files
author
zmrenwu
committed
Step4: 使用视图集简化代码
1 parent 49a8c90 commit bdaba48

File tree

4 files changed

+16
-2
lines changed

4 files changed

+16
-2
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ $ git clone https://github.com/HelloGitHub-Team/HelloDjango-REST-framework-tutor
192192
3. [初始化 RESTful API 风格的博客系统](https://www.zmrenwu.com/courses/django-rest-framework-tutorial/materials/92/)
193193
4. [实现博客首页文章列表 API](https://www.zmrenwu.com/courses/django-rest-framework-tutorial/materials/93/)
194194
5. [用类视图实现首页 API](https://www.zmrenwu.com/courses/django-rest-framework-tutorial/materials/94/)
195+
6. [使用视图集简化代码](https://www.zmrenwu.com/courses/django-rest-framework-tutorial/materials/95/)
195196

196197
## 公众号
197198
<p align="center">

blog/urls.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,6 @@
1111
),
1212
path("categories/<int:pk>/", views.CategoryView.as_view(), name="category"),
1313
path("tags/<int:pk>/", views.TagView.as_view(), name="tag"),
14-
path("api/index/", views.IndexPostListAPIView.as_view()),
14+
# path("api/index/", views.IndexPostListAPIView.as_view()),
15+
path("api/index/", views.index),
1516
]

blog/views.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from django.db.models import Q
33
from django.shortcuts import get_object_or_404, redirect, render
44
from django.views.generic import DetailView, ListView
5-
from rest_framework import status
5+
from rest_framework import mixins, status, viewsets
66
from rest_framework.decorators import api_view
77
from rest_framework.generics import ListAPIView
88
from rest_framework.pagination import PageNumberPagination
@@ -72,3 +72,12 @@ class IndexPostListAPIView(ListAPIView):
7272
queryset = Post.objects.all()
7373
pagination_class = PageNumberPagination
7474
permission_classes = [AllowAny]
75+
76+
77+
class PostViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
78+
serializer_class = PostListSerializer
79+
queryset = Post.objects.all()
80+
permission_classes = [AllowAny]
81+
82+
83+
index = PostViewSet.as_view({"get": "list"})

blogproject/urls.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,11 @@
1818
from rest_framework import routers
1919

2020
from blog.feeds import AllPostsRssFeed
21+
import blog.views
2122

2223
router = routers.DefaultRouter()
24+
router.register(r"posts", blog.views.PostViewSet, basename="post")
25+
2326
urlpatterns = [
2427
path("admin/", admin.site.urls),
2528
path("search/", include("haystack.urls")),

0 commit comments

Comments
 (0)