django-rest-frameword
过滤器的认识主要分三类,官网文档
1、安装
pip install django-filter
2、把django_filters
注册到app
中
3、对REST_FRAMEWORK
基本配置
# REST_FRAMEWORK的配置
REST_FRAMEWORK = {
# 分页显示
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10,
# 配置过滤
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
1、在视图层使用
from django_filters.rest_framework import DjangoFilterBackend
class GoodListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
queryset = Goods.objects.all()
serializer_class = GoodsSerializersModel
# 使用过滤器
filter_backends = (DjangoFilterBackend,)
# 定义需要使用过滤器的字段
filter_fields = ('name', 'market_price')
2、别的保持不变
有时候需要在过滤器中写上业务逻辑,就需要自己写一个过滤器
1、自创建一个filter.py
文件
import django_filters
from .models import Goods
class GoodsFilter(django_filters.rest_framework.FilterSet):
"""
自定义过滤类
"""
price_min = django_filters.NumberFilter(name='shop_price', lookup_expr='gte')
price_max = django_filters.NumberFilter(name='shop_price', lookup_expr='lte')
class Meta:
model = Goods
fields = ['price_min', 'price_max']
2、在视图中使用过滤器
from .filters import GoodsFilter
class GoodListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
queryset = Goods.objects.all()
serializer_class = GoodsSerializersModel
# 使用过滤器
filter_backends = (DjangoFilterBackend,)
# 定义需要使用过滤器的字段
# filter_fields = ('name', 'market_price')
filter_class = GoodsFilter
1、自己定义搜索的
class GoodsFilter(django_filters.rest_framework.FilterSet):
"""
自定义过滤类
"""
price_min = django_filters.NumberFilter(name='shop_price', lookup_expr='gte')
price_max = django_filters.NumberFilter(name='shop_price', lookup_expr='lte')
"""
icontains前面的i表示忽视大小写
"""
name =django_filters.CharFilter(name='name', lookup_expr='icontains')
class Meta:
model = Goods
fields = ['price_min', 'price_max', 'name']
2、使用自带的过滤器
from rest_framework import status, mixins, generics, viewsets,filters
class GoodListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
queryset = Goods.objects.all()
serializer_class = GoodsSerializersModel
# 使用过滤器
filter_backends = (filters.SearchFilter,)
# 定义搜索的字段
search_fields = ('name',)
3、搜索的限制
^name
开头匹配=name
完全匹配name$
表示以什么结尾1、使用
class GoodListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
queryset = Goods.objects.all()
serializer_class = GoodsSerializersModel
# 使用过滤器
filter_backends = (filters.OrderingFilter,)
# 排序的字段
ordering_fields = ('add_time','goods_num')