安装
pip install django-filter
2.安装到app
INSTALLED_APPS = [
‘django_filters’,
]
class WithDrawViewset(mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
serializer_class = WithDrawSerializer
'状态,时间范围,金额范围'
filter_backends = (DjangoFilterBackend,)
filter_class = OrdersFilter # 自定义过滤器
3 OrdersFilter
from django_filters import rest_framework as filters
from .models import OrderInfo
class OrdersFilter(filters.FilterSet):
min_price = filters.NumberFilter(field_name=‘total_amount’, lookup_expr=‘gte’)
max_price = filters.NumberFilter(field_name=“total_amount”, lookup_expr=‘lte’, help_text=“最大金额”)
pay_status = filters.CharFilter(field_name=‘pay_status’, lookup_expr=‘icontains’)
order_no = filters.CharFilter(field_name=“order_no”, help_text=“订单名称模糊查询”)
user_msg = filters.CharFilter(field_name=“user_msg”, lookup_expr=‘icontains’)
min_time = filters.DateTimeFilter(field_name=‘add_time’, lookup_expr=‘gte’)
max_time = filters.DateTimeFilter(field_name=‘add_time’, lookup_expr=‘lte’)
class Meta:
model = OrderInfo
fields = ['min_price', 'max_price', 'order_no', 'min_time', 'max_time', 'user_msg']
原创于:http://www.debug5.com/detail/18/
程序猿的道德修养:
本博客源码Github地址:
https://github.com/whisnos/myblog
(仅供学习使用)请随手给个star,谢谢