分类筛选过滤器
分类筛选过滤器
>: pip install django-filter
二、分类筛选过滤器
# 分类筛选:django-filter:filter_backends配置DjangoFilterBackend,再在filter_fields中配置分组筛选的字段
from django_filters.rest_framework import DjangoFilterBackend
class FreeCourseListAPIView(ListAPIView):
queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders').all()
serializer_class = serializers.FreeCourseModelSerializer
# 自定义过滤器
filter_backends = [DjangoFilterBackend]
# 参与分类筛序的字段,所有字段都可以,但是分组字段要有意义
# 分类字段是要序列化的字段获取序列化字段中的字段,就可以直接分类
# http://127.0.0.1:8000/course/free?course_category=2
filter_fields = ["course_category"] # 要筛选的字段(序列化字段)
三、 自定义区间删选过滤器
# 参考DjangoFilterBackend类中
if filterset_fields and queryset is not None:
MetaBase = getattr(self.filterset_base, 'Meta', object)
class AutoFilterSet(self.filterset_base):
class Meta(MetaBase):
model = queryset.model
fields = filterset_fields
return AutoFilterSet
# 1.自定义区间过滤器类
# 基于django-filter插件,完成指定区间筛选(一般都是对应数字字段)
from django_filters.rest_framework.filterset import FilterSet
from django_filters import filters
from . 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"]
# 2.使用
# 自定义的区间筛序选过滤器
from .filters import CourseFilterSet
class FreeCourseListAPIView(ListAPIView):
queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders').all()
serializer_class = serializers.FreeCourseModelSerializer
# 自定义类
filter_class = CourseFilterSet
# eg: http://127.0.0.1:8000/course/free?min_price=2&max_price=100
# eg: http://127.0.0.1:8000/course/free?course_category=2
自定义filter类时的字段
models.AutoField: {'filter_class': NumberFilter},
models.CharField: {'filter_class': CharFilter},
models.TextField: {'filter_class': CharFilter},
models.BooleanField: {'filter_class': BooleanFilter},
models.DateField: {'filter_class': DateFilter},
models.DateTimeField: {'filter_class': DateTimeFilter},
models.TimeField: {'filter_class': TimeFilter},
models.DurationField: {'filter_class': DurationFilter},
models.DecimalField: {'filter_class': NumberFilter},
models.SmallIntegerField: {'filter_class': NumberFilter},
models.IntegerField: {'filter_class': NumberFilter},
models.PositiveIntegerField: {'filter_class': NumberFilter},
models.PositiveSmallIntegerField: {'filter_class': NumberFilter},
models.FloatField: {'filter_class': NumberFilter},
models.NullBooleanField: {'filter_class': BooleanFilter},
models.SlugField: {'filter_class': CharFilter},
models.EmailField: {'filter_class': CharFilter},
models.FilePathField: {'filter_class': CharFilter},
models.URLField: {'filter_class': CharFilter},
models.GenericIPAddressField: {'filter_class': CharFilter},
models.CommaSeparatedIntegerField: {'filter_class': CharFilter},
models.UUIDField: {'filter_class': UUIDFilter},
在当下的阶段,必将由程序员来主导,甚至比以往更甚。