当前位置: 首页 > 工具软件 > Filter View > 使用案例 >

django-filter过滤查找(模糊查询)

夏侯朝斑
2023-12-01

1.安装

pip insall django-filter

django-filters⽀持的pytho和django版本:
Python: 3.5, 3.6, 3.7, 3.8
Django: 1.11, 2.0, 2.1, 2.2, 3.0
DRF: 3.10+

2.settings中配置

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

在视图中使用

class BookListView(ListAPIView):
 queryset = BookInfo.objects.all()
 serializer_class = BookInfoSerializer
 #指定查询字段
 filter_fields = ('btitle', 'bread')
 #请求以问号传参
# 127.0.0.1:8000/books/?btitle=⻄游记

#自定义过滤类

import django_filters
from django_filters import rest_framework as filters

from App.models import Bookinfo


class BookFilter(django_filters.FilterSet):
    class Meta:
        # http://127.0.0.1:8000/book/?min_read=10&max_read=50
        # field_name="bread" 模型中的字段名;lookup_expr是运算,gte表示>=
        min_read = filters.NumberFilter(field_name="bread", lookup_expr='gte')
        max_read = filters.NumberFilter(field_name="bread", lookup_expr='lte')
        model = Bookinfo  # 模型
        fields = {
            'btitle':['icontains'],  # 键是字段名,列表里是查询进行运算
             # http://127.0.0.1:8000/book/?bcomment__gte=30&bcomment__lte=60
            'bcomment':['gte','lte'],
        }

调用

#IndexView.py
class IndexView(ListAPIView):
 """⾸⻚"""
 serializer_class = BookInfoSerializer
 queryset = BookInfo.objects.all()
 filter_class = BookFilter #指定过滤类

过滤字段参考

https://blog.csdn.net/qq_43665151/article/details/104850673

 类似资料: