過濾模塊

過濾模塊

安裝
>: 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
相關文章
相關標籤/搜索