25.过滤模块

过滤模块

安装
>: pip install django-filter
注册应用:settings/dev.py
INSTALLED_APPS = [
    # 列表过滤模块
    'django_filters',  
]

条件过滤

视图函数:course/views.py
from django_filters.rest_framework import DjangoFilterBackend
class CourseAPIView(ListAPIView):
    """课程列表接口"""
    queryset = Course.objects.filter(is_delete=False, is_show=True).order_by("-orders")
    serializer_class = CourseSerializer
    # 条件过滤:DjangoFilterBackend
    filter_backends = [DjangoFilterBackend]
    # 过滤字段
    filter_fields = ['course_category', ]
接口
http://127.0.0.1:8000/course/?course_category=1

排序过滤

视图函数:course/views.py
from rest_framework.filters import OrderingFilter
from .pagination import CoursePageNumberPagination
class CourseAPIView(ListAPIView):
    """课程列表接口"""
    queryset = Course.objects.filter(is_delete=False, is_show=True).order_by("-orders")
    serializer_class = CourseSerializer
    # 排序过滤:OrderingFilter
    filter_backends = [OrderingFilter]
    # 过滤字段
    ordering_fields = ['id', 'students', 'price']
接口
http://127.0.0.1:8000/course/?ordering=price
http://127.0.0.1:8000/course/?ordering=-price
posted @ 2021-01-10 22:20  ABDM  阅读(62)  评论(0编辑  收藏  举报