reful实现分页、过滤、搜索、软删除

一、分页

1.配置setting.py

REST_FRAMEWORK = {
    # 实现分页
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 2,

二、搜索

1.配置setting.py

# 配置restful api 返回结果
REST_FRAMEWORK = {
    # 实现过滤
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',
                                'rest_framework.filters.SearchFilter'),
}

2.在views中加入过滤功能

class StudentEdit(mixins.ListModelMixin,
                  mixins.RetrieveModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.DestroyModelMixin,
                  mixins.CreateModelMixin,
                  viewsets.GenericViewSet):

    # 查询所有信息
    queryset = Student.objects.all()
    # 序列化
    serializer_class = StudentSerializer
    # 筛选/搜索
    filter_class = StuFilter

3.创建类,继承filters.FilterSet类

变量名 = django_filters.CharFilter(参数1,参数2),参数1时数据库的属性名,参数2可以指定匹配模式,如icontains模糊匹配,如果想要精确匹配,不需要设置第二个参数。

import django_filters
from rest_framework import filters

from stu.models import Student


class StuFilter(filters.FilterSet):
    # 自定义过滤信息
    # 在Student中获取s_name = 指定内容的记录
    # lookup_expr 指定匹配模式 icontains 模糊匹配
    name = django_filters.CharFilter('s_name', lookup_expr='icontains')
    tel = django_filters.CharFilter('s_tel')
    status = django_filters.CharFilter('s_status')
    # 查询数据库中s_operate_time 大于获取的operate_time_min
    operate_time_min = django_filters.DateTimeFilter('s_operate_time', lookup_expr='gt')
    # 查询数据库中s_operate_time 小于获取的operate_time_max
    opertate_time_max = django_filters.DateTimeFilter('s_operate_time', lookup_expr='lt')
    yuwen_min = django_filters.NumberFilter('s_yuwen', lookup_expr='gte')
    yuwen_max = django_filters.NumberFilter('s_yuwen', lookup_expr='lte')

    class Meta:
        model = Student
        # fields中的参数可以不写
        fields = ['s_name', 's_tel']

三、过滤

# 过滤数据
    def get_queryset(self):
        query = self.queryset
        # 只显示未删除的学生,即s_delete=0
        # 按照id递减排序显示
        return query.filter(s_delete=0).order_by('-id')

四、软删除

软删除意思就是当操作删除一条记录时并不是真正的删除,而是修改这个记录delete属性的值,通常delete取布尔值,true表示已经删除,false表示未删除。

1.在模型中增加属性存储delete的值

s_delete = models.BooleanField(default=0)

2.重写destory方法

# 软删除 重构destory方法
    def destroy(self, request, *args, **kwargs):
        # 获取实例对象
        instance = self.get_object()
        instance.s_delete = 1
        instance.save()
        return Response({'msg': '删除成功', 'code': 200})

你可能感兴趣的:(reful实现分页、过滤、搜索、软删除)