django的分类过滤,区间过滤
Django-filter插件
安装
>: pip install django-filter
分类过滤
"""
方式一
1)在视图文件views.py中导入django-filter的功能组件
from django_filters.rest_framework import DjangoFilterBackend
2)将搜索组件配置给群查接口视图类的filter_backends
filter_backends = [DjangoFilterBackend]
3)配置视图类关联的Model表可以分类的字段(通常是可以分组的字段)
filter_fields = ['course_category']
4)前台访问该群查接口,采用拼接参数方式用分类course_category字段将分类条件提供给后台
http://127.0.0.1:8000/course/free/?course_category=1 # 拿课程分类1下的所有课程
方式二
1)自定义过滤类继承django-filter插件的FilterSet类,绑定Model表,并设置分类字段
from django_filters.filterset import FilterSet
from . import models
class CourseFilterSet(FilterSet):
class Meta:
model = models.Course
fields = ['course_category']
2)在视图文件views.py中导入django-filter的功能组件及自定义的过滤类
from django_filters.rest_framework import DjangoFilterBackend
from .filters import CourseFilterSet
3)将搜索组件配置给群查接口视图类的filter_backends
filter_backends = [DjangoFilterBackend]
4)配置视图类关联的自定义过滤类
filter_class = CourseFilterSet
5)前台访问该群查接口,采用拼接参数方式用分类course_category字段将分类条件提供给后台
http://127.0.0.1:8000/course/free/?course_category=1 # 拿课程分类1下的所有课程
"""
区间过滤
"""
1)自定义过滤类继承django-filter插件的FilterSet类,绑定Model表,并设置自定义区间规则字段
from django_filters.filterset import FilterSet
from . import models
class CourseFilterSet(FilterSet):
# 区间过滤:field_name关联的Model字段;lookup_expr设置规则;gt是大于,gte是大于等于;
min_price = filters.NumberFilter(field_name='price', lookup_expr='gte')
max_price = filters.NumberFilter(field_name='price', lookup_expr='lte')
class Meta:
model = models.Course
fields = ['min_price', 'max_price']
2)在视图文件views.py中导入django-filter的功能组件及自定义的过滤类
from django_filters.rest_framework import DjangoFilterBackend
from .filters import CourseFilterSet
3)将搜索组件配置给群查接口视图类的filter_backends
filter_backends = [DjangoFilterBackend]
4)配置视图类关联的自定义过滤类
filter_class = CourseFilterSet
5)前台访问该群查接口,采用拼接参数方式用自定义区间规则字段将区间条件提供给后台
http://127.0.0.1:8000/course/free/?min_price=30&max_price=60 # 拿课程价格在30~60的所有课程
"""
Only you can control your future
You're not alone. You still have family,peopel who care for you and want to save you.