rest配置分页
# rest配置
REST_FRAMEWORK = {
# 分页配置
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
# 设置一页的条数
'PAGE_SIZE': 2,
}
接口返回的数据
"count": 7,
"next": "http://127.0.0.1:8080/api/article/art/?page=2",
"previous": null,
"results": [
{
"id": 2,
"title": "标题1 ",
"desc": "描述1 ",
"content": "内容1 ",
"atype": "python"
},
{
"id": 3,
"title": "标题啊啊",
"desc": "来点描述",
"content": "这里搞点正文",
"atype": "C"
}
]
处理patch访问时的空值
from rest_framework import serializers
from article.models import Article
class ArticleSerializer(serializers.ModelSerializer):
desc = serializers.CharField(min_length=2,
max_length=100,
error_messages={
'required': '描述必填',
'max_length': '描述不超过100个字符',
'min_length': '描述不少于两个字符'
})
title = serializers.CharField(min_length=2,
max_length=100,
error_messages={
'required': '标题必填',
'min_length': '标题不少于两个字符',
'max_length': '标题不超过100个字符'
})
content = serializers.CharField(min_length=5,
error_messages={
'required': '内容必填',
'min_length': '内容不少于5个字符'
})
class Meta:
# 序列化的模型
model = Article
# 需要序列化的字段
fields = ['id', 'title', 'desc', 'content', 'atype']
过滤
安装过滤的库
pip install django-filter
配置settings.py文件
# rest配置
REST_FRAMEWORK = {
# 分页配置
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
# 设置一页的条数
'PAGE_SIZE': 2,
# 配置过滤
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',
'rest_framework.filters.SearchFilter'),
}
在views中指定filter_class
class ArticleView(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.DestroyModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin):
# 查询返回的数据
queryset = Article.objects.filter(is_delete=0)
# 序列化返回的文章数据
serializer_class = ArticleSerializer
# 过滤
filter_class = ArticleFilter
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')
# 过滤URL中content参数
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']
多对多关联关系过滤
修改序列化类
序列化时会默认调用to_representation方法,返回的结果为当前的instance对象的序列化结果
from rest_framework import serializers
from article.models import Article
class ArticleSerializer(serializers.ModelSerializer):
desc = serializers.CharField(min_length=2,
max_length=100,
error_messages={
'required': '描述必填',
'max_length': '描述不超过100个字符',
'min_length': '描述不少于两个字符'
})
title = serializers.CharField(min_length=2,
max_length=100,
error_messages={
'required': '标题必填',
'min_length': '标题不少于两个字符',
'max_length': '标题不超过100个字符'
})
content = serializers.CharField(min_length=5,
error_messages={
'required': '内容必填',
'min_length': '内容不少于5个字符'
})
class Meta:
# 序列化的模型
model = Article
# 需要序列化的字段
fields = ['id', 'title', 'desc', 'content', 'atype']
def to_representation(self, instance):
# 序列化时会默认调用该方法,返回的结果为当前的instance对象的序列化结果
data = super().to_representation(instance)
if instance.atype:
data['atype'] = instance.atype.t_name
return data
自定义返回数据格式
配置自定义render
# rest配置
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',
)
}
修改在settings中指定的自定义render类
from rest_framework.renderers import JSONRenderer
class CustomRenderer(JSONRenderer):
"""
重构返回结果的函数
{
'code': 200,
'msg': '请求成功',
'data': {
}
}
"""
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)
views.py文件内容
from django.shortcuts import render
from rest_framework import mixins, viewsets, status
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.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)
# def get_queryset(self):
# search_title = self.request.GET.get('title')
# search_desc = self.request.GET.get('desc')
# search_content = self.request.GET.get('content')
# # 既要搜索title, desc,content
# if not search_title and not search_desc and not search_content:
# return self.queryset
# return self.queryset.filter(title__contains=search_title)