注意 : 都是GenericAPIView或子类进行的操作
pip install django-filter
在配置文件中增加过滤后端的设置:
#settings.py
INSTALLED_APPS = [ ... ‘django_filters‘, # 需要注册应用, ] REST_FRAMEWORK = { ... ‘DEFAULT_FILTER_BACKENDS‘: (‘django_filters.rest_framework.DjangoFilterBackend‘,) }
在视图中添加filter_fields属性,指定可以过滤的字段
from django_filter.rest-framework import DjangoFilterBackend class BookListView(ListAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer #接口:/api/cars/?priece=90000&bread=1 filter_fields = (‘btitle‘, ‘bread‘) # 127.0.0.1:8000/books/?btitle=西游记
from django_filter.rest-framework import DjangoFilterBackend from reset_framework.filter SeachFilter filter_backends = [DjangoFileterBackend,SearchFilter] #接口:/api/cars/?search=9 代表9在name或price直进行模糊查询 search_fileds = (‘name‘,‘price‘)
原文:https://www.cnblogs.com/HZLS/p/11406332.html