drf过滤器、分页器、筛选器的应用

一、drf 提供的过滤器(ordering)

views.py


from rest_framework.generics import ListAPIView
from . import models, serializers

# OrderingFilter排序
from rest_framework.filters import OrderingFilter,

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer

    # 配置过滤器类
    filter_backends = [OrderingFilter,]
    # 参与排序的字段: ordering=-price, id
    ordering_fields = ['price', 'id']

请求的url为http://127.0.0.1:8000/course/free?ordering=-price,id

二、自定义过滤器

以获取的数据条数为例

filters.py

# 继承BaseFilterBackend
from rest_framework.filters import BaseFilterBackend

class LimitFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        # 获取前台想要的数据条数
        limit = request.query_params.get('limit')
        try:
            return queryset[:int(limit)]
        except:
            return queryset

views.py


from rest_framework.generics import ListAPIView
from . import models, serializers

# OrderingFilter排序
from rest_framework.filters import OrderingFilter,
from .filters import LimitFilter

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer

    # 配置过滤器类, 自定义过滤器类可与自带的共用
    filter_backends = [OrderingFilter, LimitFilter]  # LimitFilter为自定义过滤器
    # 参与排序的字段: ordering=-price,id
    ordering_fields = ['price']

三、群查搜索过滤器

views.py


from rest_framework.generics import ListAPIView
from . import models, serializers

# SearchFilter搜索过滤器
from rest_framework.filters import SearchFilter

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer

    # 配置搜索过滤器类
    filter_backends = [SearchFilter]
    # 参与搜索的字段: search = python (意思是name字段中带python就可以了)
    search_fields = ['name']

请求的url为:http://127.0.0.1:8000/course/free?search=python

四、drf分页器(pagination)

paginations.py

需自定义参数

# 继承分页器类
from rest_framework.pagination import PageNumberPagination

class CoursePageNumberPagination(PageNumberPagination):
    # 默认一页显示的条数
    page_size = 2
    # 选择哪一页的key,在url中?page=2,代表第二页
    page_query_param = 'page'
    # 用户自定义一页条数
    page_size_query_param = 'page_size'
    # 用户自定义一页最大控制条数
    max_page_size = 10

views.py


from rest_framework.generics import ListAPIView
from . import models, serializers

from .paginations import CoursePageNumberPagination

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer

    # 分页器
    pagination_class = CoursePageNumberPagination

请求的url为http://127.0.0.1:8000/course/free?page=1

五、偏移条数分页器(了解)

paginations.py

from rest_framework.pagination import LimitOffsetPagination

class CourseLimitOffsetPagination(LimitOffsetPagination):
    # 默认一页条数
    default_limit = 2
    # 从offset开始往后显示limit条
    limit_query_param = 'limit'
    offset_query_param = 'offset'
    # 最大一页最大条数
    max_limit = 2

views.py

from rest_framework.generics import ListAPIView
from . import models, serializers

from .paginations import CourseLimitOffsetPagination

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer

    # 偏移分页器
    pagination_class = CourseLimitOffsetPagination

请求的url:http://127.0.0.1:8000/course/free?limit=1&offset=2

六、分类筛选过滤器

1.普通使用筛选

views.py


from rest_framework.generics import ListAPIView
from . import models, serializers

# 分类筛选过滤器 pip install django-filter
from django_filters.rest_framework import DjangoFilterBackend

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer

    # 配置过滤器类
    filter_backends = [DjangoFilterBackend,]
    # 参与分类筛选的字段
    filter_fields = ['course_category']

请求的url: http://127.0.0.1:8000/course/free?course_category=1

2.区间筛选(高级使用)

filters.py

基于django-filter插件,完成指定区间筛选(一般都是对应)数字字段

from django_filters.rest_framework.filterset import FilterSet
from django_filters import filters
from . import models
class CourseFilterSet(FilterSet):
    # 自定义筛选字段    lte代表 <=  小于等于
    max_price = filters.NumberFilter(field_name='price', lookup_expr='lte')
    # gte 代表 >= 大于等于
    min_price = filters.NumberFilter(field_name='price', lookup_expr='gte')
    class Meta:
        # 关联要筛选的表
        model = models.Course
        # 参与筛选的字段  可以是自定义字段,也可以是表中字段
        fields = ['course_category', 'max_price', 'min_price']

views.py


from rest_framework.generics import ListAPIView
from . import models, serializers

# 自定义筛选器
from .filters import CourseFilterSet

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()
    serializer_class = serializers.FreeCourseModelSerializer
    # 自定义筛选类
    filter_class = CourseFilterSet

请求的url: http://127.0.0.1:8000/course/free?max_price=100&min_price=30

posted @ 2019-12-07 17:50  tomjoy  阅读(588)  评论(0编辑  收藏  举报