django restfreamwork过滤,搜索和排序

安装django-filters 在setting INSTALL_APP注册  

自定义filter相关代码

import django_filters
from django.db.models import Q
from .models import Goods

class GoodsFilter(django_filters.rest_framework.FilterSet):
 """
 商品的过滤类
 """
      pricemin = django_filters.NumberFilter(name='shop_price', help_text="最低价格",lookup_expr='gte')
      pricemax = django_filters.NumberFilter(name='shop_price', lookup_expr='lte')
      top_category = django_filters.NumberFilter(method='top_category_filter')

       def top_category_filter(self, queryset, name, value):
            return queryset.filter(Q(category_id=value)Q(category__parent_category_id=value)Q(category__parent_category__parent_category_id=value))

       class Meta:
             model = Goods
             fields = ['pricemin', 'pricemax', 'is_hot', 'is\_new']

  相关view代码

from django_filters.rest_framework import DjangoFilterBackend 
from rest_framework import filters 下面内容插入到要过滤的view中

filter_backends= (DjangoFilterBackend,filters.SearchFilter, filters.OrderingFilter)
#要过滤的,填写过滤器
filter_class = GoodsFilter
 #要搜索的字段
 search_fields = ('name', 'goods_brief', 'goods_desc')
#要排序的字段
ordering_fields = ('sold_num', 'shop_price')


django restfreamwork过滤,搜索和排序
http://www.jcwit.com/article/183/
作者
Carlos
发布于
2018年7月11日
许可协议