1、添加到app裏面django
INSTALLED_APPS = [ 'django_filters', ]
2、新建filter.pyapp
# goods/filters.py import django_filters from .models import Goods class GoodsFilter(django_filters.rest_framework.FilterSet): ''' 商品過濾的類 ''' #兩個參數,name是要過濾的字段,lookup是執行的行爲,‘小與等於本店價格’ 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']
3、views.pyspa
from .filters import GoodsFilter from django_filters.rest_framework import DjangoFilterBackend class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet): '商品列表頁' #這裏必需要定義一個默認的排序,不然會報錯 queryset = Goods.objects.all().order_by('id') # 分頁 pagination_class = GoodsPagination serializer_class = GoodsSerializer filter_backends = (DjangoFilterBackend,) # 設置filter的類爲咱們自定義的類 filter_class = GoodsFilter