You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

59 lines
2.0 KiB

from rest_framework import viewsets
from article.serializers import ArticleSerializer, CategorySerializer, CategoryDetailSerializer
from article.serializers import TagSerializer, ArticleDetailSerializer, AvatarSerializer
from article.models import Article, Category, Tag, Avatar
from article.permissions import IsAdminUserOrReadOnly
from rest_framework.filters import SearchFilter
class ArticleViewSet(viewsets.ModelViewSet):
"""文章视图集"""
queryset = Article.objects.all()
serializer_class = ArticleSerializer
permission_classes = [IsAdminUserOrReadOnly]
filter_backends = [SearchFilter, ]
# http://127.0.0.1:8000/api/article/?author__username=admin&title=第一篇文章
# filter_fields = ['title', 'author__username',] # 精确查询
# 下面两种字段都可以使用模糊查询
search_fields = ('title', 'author__username')
def perform_create(self, serializer):
# 在创建文章前,提供了视图集无法自行推断的用户外键字段。
serializer.save(author=self.request.user)
def get_serializer_class(self):
if self.action == 'list':
return ArticleSerializer
else:
return ArticleDetailSerializer
class CategoryViewSet(viewsets.ModelViewSet):
"""分类视图集"""
queryset = Category.objects.all()
serializer_class = CategorySerializer
permission_classes = [IsAdminUserOrReadOnly]
pagination_class = None # 不进行翻页
def get_serializer_class(self):
if self.action == 'list':
return CategorySerializer
else:
return CategoryDetailSerializer
class TagViewSet(viewsets.ModelViewSet):
"""标签视图集"""
queryset = Tag.objects.all()
serializer_class = TagSerializer
permission_classes = [IsAdminUserOrReadOnly]
pagination_class = None # 不进行翻页
class AvatarViewSet(viewsets.ModelViewSet):
"""标题图片视图集"""
queryset = Avatar.objects.all()
serializer_class = AvatarSerializer
permission_classes = [IsAdminUserOrReadOnly]