drf框架中过滤数据
07-04 过滤组件
安装:
pip install django-filter
使用:
视图类中导入DjangoFilterBackend
# views.py
from rest_framework.generics import ListAPIView
from django_filters.rest_framework import DjangoFilterBackend
class MyListAPIView(ListAPIView):
filter_backends = [DjangoFilterBackend]
# 参与筛选的字段
filter_fields = ['course_category']
...
# 前端请求方式:在url中拼接字段参数
# 例如:http://127.0.0.1:8000/api/?course_category=1
自定义过滤类:
# filters.py
from django_filters.rest_framework import FilterSet
from django_filters import filters
from course import models
# 自定义筛选条件
class CourseFilterSet(FilterSet):
"""自定义筛选条件"""
max_price = filters.NumberFilter(field_name='price', lookup_expr='lte')
min_price = filters.NumberFilter(field_name='price', lookup_expr='gte')
class Meta:
model = models.Course
fields = ['course_category', 'max_price', 'min_price']
views.py中配置filter_class
# views.py
from rest_framework.generics import ListAPIView
from django_filters.rest_framework import DjangoFilterBackend
from . filters import CourseFilterSet
class MyListAPIView(ListAPIView):
filter_backends = [DjangoFilterBackend]
# 参与筛选的类
filter_class = CourseFilterSet
...
# 前端请求方式:在url中拼接字段参数
# 例如:http://127.0.0.1:8000/api/?min_price=10&max_price=100