浮躁是人生最大的敌人

过滤模块

Posted on 2019-07-24 00:11  King'home  阅读(252)  评论(0编辑  收藏  举报

过滤模块

安装
>: 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

Copyright © 2024 King'home
Powered by .NET 9.0 on Kubernetes