from rest_framework.filters import SearchFilter
python
from rest_framework.viewsets import ModelViewSet from rest_framework.filters import SearchFilter class CarModelViewSet(ModelViewSet): queryset = ..... serializer_class = ..... search_fields = ['字段一名稱','字段二名稱'] #能夠用()包裹,寫前面的優先級大於後面 filter_backends = [SearchFilter,]
其中search_fields前面
添加各類字符來限制搜索行爲mysql
^
以指定內容開頭=
徹底匹配@
全文搜索(目前只支持django數據存放在mysql)$
正則匹配from django_filters.rest_framework import FilterSet from django_filters import filters from . import models class CarFilterSet(FilterSet): min_price = filters.NumberFilter(field_name='類裏面的字段名稱', lookup_expr='gte') #gte爲大於等於 max_price = filters.NumberFilter(field_name='類裏面的字段名稱', lookup_expr='lte')#lte爲小於等於 class Meta: model = 字段所在的類名 # brand仍是實現分類 # min_price,max_price能夠定義區間 fields = ['brand', 'min_price', 'max_price'] #上面的min_price以及max_price爲咱們提交數據的key
from rest_framework.viewsets import ModelViewSet from django_filters.rest_framework import DjangoFilterBackend class CarModelViewSet(ModelViewSet): queryset = ..... serializer_class = ..... filter_class = CarFilterSet #咱們自定義的對象,前提要將其導入到咱們程序所在的窗口 filter_backends =[DjangoFilterBackend,]
from rest_framework.viewsets import ModelViewSet from rest_framework.filters import OrderingFilter class CarModelViewSet(ModelViewSet): queryset = ..... serializer_class = ..... ordering_fields = ['字段一名稱','字段二名稱'] #能夠用()包裹,寫前面的優先級大於後面 filter_backends =[DjangoFilterBackend,]