Django_rest-framework过滤

文章目录

    • 安装
    • 配置sttings
    • 自定义过滤类
    • 指定过滤字段和过滤类

安装

pip insall django-filter

配置sttings

INSTALLED_APPS = [
     ...
    'django_filters',  # 需要注册应⽤, 
]
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS':
('django_filters.rest_framework.DjangoFilterBackend',)
}

自定义过滤类

	from django_filters import rest_framework as filters

from App.models import Bookinfo




class BookFilter(filters.FilterSet):
    # 查询字段名不要求和模型中一模一样
    # field_name 模型中的字段名
    # method 查询方法
    # http://127.0.0.1:9090/list/?comment=50
    comment = filters.NumberFilter(field_name='bcomment', method='find_comment')

    class Meta:
        model = Bookinfo

        fields = {
            # 运算符和ORM中运算符一模一样
            #http://127.0.0.1:9008/list/?btitle__icontains=%E5%85%AB
            'btitle':['icontains','startswith','iendswith'],  # 不区分大小写的包含
            # http://127.0.0.1:9008/list/?bread__gt=10&bread__lt=50
            'bread':['exact','lt','gt','lte','in'],
        }

    def find_comment(self,queryset,name,value):
        """
        :param queryset:
        :param name: 查询字段名
        :param value: 查询的值
        :return: queryset(一定要返回queryset)
        """
        print(name,value)
        return queryset.filter(bcomment__lt=value)

指定过滤字段和过滤类

class BooksView(ListAPIView):
    """
    图书分页显示
    """
    queryset = Bookinfo.objects.all()
    serializer_class = BookinfoSerializer
    # 指定过滤字段
    filter_fields = ('btitle','bread')
    # 指定过滤类
    filter_class = BookFilter

你可能感兴趣的:(Django,django,python)