from rest_framework.generics import ListAPIView,CreateAPIView,UpdateAPIView,RetrieveAPIView,DestroyAPIView
from rest_framework.filters import BaseFilterBackend
from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination
from newapi import models
class ArticleSerializer(serializers.ModelSerializer):
author_name = serializers.CharField(source="author.username",required=False)
class Meta:
model = models.Article
exclude = ['author']
class ArticleFilter(BaseFilterBackend):
"""
查询:根据URL中的cagetory参数查询
"""
def filter_queryset(self, request, queryset, view):
val = request.query_params.get('cagetory')
if val:
return queryset.filter(category = val)
return queryset
class ArticleView(ListAPIView,CreateAPIView):
# queryset对象
queryset = models.Article.objects.all()
# 序列化
serializer_class = ArticleSerializer
# 筛选规则
filter_backends = [ArticleFilter,]
# 分页
pagination_class = PageNumberPagination
def perform_create(self,serializer):
serializer.save(author_id=2)