一、分页
1.修改settings.py配置文件,增加分页的配置信息
REST_FRAMEWORK = {
# 分页配置
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
# 设置一页的条数
'PAGE_SIZE': 2,
}
2.注意:在结果data对应的value值中,有一个count的key,表示返回数据有多少条,next表示下一页的url,previous表示上一页的url。
二、过滤
1.修改settings.py配置文件,增加filter过滤的信息
REST_FRAMEWORK = {
# 分页配置
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 2,
# 配置过滤
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',
'rest_framework.filters.SearchFilter'),
}
2.views.py文件中指定filter_class
from article.article_filter import ArticleFilter
class ArticleView(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.DestroyModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin):
queryset = Article.objects.all().filter(is_delete=0)
serializer_class = ArticleSerializer
# 过滤
filter_class = ArticleFilter
3.编写filter_class过滤信息
from rest_framework import filters
import django_filters
from article.models import Article
class ArticleFilter(filters.FilterSet):
# 过滤URL中title参数
title = django_filters.CharFilter('title', lookup_expr='contains')
# 过滤URL中的desc参数
desc = django_filters.CharFilter('desc', lookup_expr='contains')
content = django_filters.CharFilter('content', lookup_expr='contains')
# 过滤URL中时间最小值min_time
min_time = django_filters.DateTimeFilter('create_time', lookup_expr='gt')
# 过滤URL中时间最大值max_time
max_time = django_filters.DateTimeFilter('create_time', lookup_expr='lt')
class Meta:
model = Article
fields = ['title', 'desc', 'content', 'min_time', 'max_time']
三、返回自定义格式的JSON数据
1.修改settings.py配置文件,增加自定义render的信息
REST_FRAMEWORK = {
# 分页配置
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 2,
# 配置过滤
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',
'rest_framework.filters.SearchFilter'),
# 配置自定义render
'DEFAULT_RENDERER_CLASSES': (
'utils.MyRender.CustomRenderer',
),
}
2.重构Serializer类的to_representation(self, instance)方法
from rest_framework import serializers
from article.models import Article, Atype
class ArticleSerializer(serializers.ModelSerializer):
desc = serializers.CharField(min_length=10,
max_length=100,
error_messages={
'required': '描述必填',
'max_length': '描述不超过10字符',
'min_length': '描述不少于3字符'
})
title = serializers.CharField(min_length=10,
error_messages={
'required': '标题必填',
})
content = serializers.CharField(min_length=10,
error_messages={
'required': '内容必填',
})
class Meta:
model = Article
fields = ['title', 'desc', 'content', 'id', 'atype']
def to_representation(self, instance):
# 序列化时会默认调用该方法,返回的结果为当前instance对象的序列化结果
data = super().to_representation(instance)
if instance.atype:
data['atype'] = instance.atype.t_name
return data
3.编写Renderer类信息
from rest_framework.renderers import JSONRenderer
class CustomRenderer(JSONRenderer):
def render(self, data,
accepted_media_type=None,
renderer_context=None):
try:
code = data.pop('code')
msg = data.pop('msg')
except:
code = 200
msg = '请求成功'
my_data = {
'code': code,
'msg': msg,
'data': data
}
return super().render(my_data, accepted_media_type=None, renderer_context=None)
4.retrieve(self, request, *args, **kwargs)方法
from django.shortcuts import render
from rest_framework import mixins, viewsets
from rest_framework.response import Response
from article.article_filter import ArticleFilter
from article.article_serializer import ArticleSerializer
from article.models import Article
class ArticleView(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.DestroyModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin):
queryset = Article.objects.all().filter(is_delete=0)
serializer_class = ArticleSerializer
filter_class = ArticleFilter
def perform_destroy(self, instance):
instance.is_delete = 1
instance.save()
def retrieve(self, request, *args, **kwargs):
try:
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response(serializer.data)
except:
data = {}
data['code'] = 500
data['msg'] = '获取数据失败'
return Response(data)