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
上一篇:Asp.Net.Core5 筛选器


下一篇:吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:自动编解码器网络的原理与实现