1.过滤下载 pip install django-filter 2.下载后注册 INSTALLED_APPS=['django_filters',] 3.导入rest_framework from django_filters import rest_framework class DoctorsFilter(rest_framework.FilterSet): authentication_classes = [TokenAuthentication] #开始时间 start_date = rest_framework.DateFilter(field_name='start_date', lookup_expr='gte') #结束时间 end_date = rest_framework.DateFilter(field_name='end_date', lookup_expr='lte') 4.在类中的使用 from django_filters.rest_framework import DjangoFilterBackend from rest_framework.viewsets import ModelViewSet
class DoctorsViewSet(ModelViewSet): filter_backends = [DjangoFilterBackend] #过滤其他的字段 filter_fields = ('id', 'patient', 'doc_type',)
#指向要过滤的类 filter_class = DoctorsFilter
2.排序
#1.导入OrderingFilter from rest_framework.filters import OrderingFilter #2.在类中的使用 class CarsModelViewSet(ModelViewSet): queryset =models的类 serializer_class=序列化组件
filter_backends = [OrderingFilter]
#/api/cars/?ordering=-id 倒序
#/api/cars/?ordering=id 正序 ordering_fields = ('id', )