django drf 过滤器

发布于:2024-10-11 ⋅ 阅读:(23) ⋅ 点赞:(0)

排序

代码:

from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter

class TestListAPIView(ListAPIView):
  queryset = models.Course.objects.filter(is_delete=False).all()
  serializer_class = serializers.TestModelSerializer

  # 配置过滤器类
  filter_backends = [OrderingFilter,]
  # 参与排序的字段: ordering=-score, id
  ordering_fields = ['id', 'score']

前端请求:

http://127.0.0.1:8000/api/test?ordering=-score,id

群查搜索过滤器

代码:

from rest_framework.generics import ListAPIView
# SearchFilter搜索过滤器
from rest_framework.filters import SearchFilter

class TestListAPIView(ListAPIView):
   queryset = models.Course.objects.filter(is_delete=False).all()
   serializer_class = serializers.FreeCourseModelSerializer

   # 配置搜索过滤器类
   filter_backends = [SearchFilter]
   # 参与搜索的字段: search = liuliuliu (意思是name、status、create_by字段中带liuliuliu就可以了)
   search_fields = ['name', 'status', 'create_by']

前端请求:

http://127.0.0.1:8000/api/test?search=liuliuliu

自定义过滤器

自定义过滤器代码:

from rest_framework.filters import BaseFilterBackend

class MyFilter(BaseFilterBackend):
   def filter_queryset(self, request, queryset, view):
       # 例如:获取前端想要的数据条数
       limit = request.query_params.get('limit')
       try:
           return queryset[:int(limit)]
       except:
           return queryset

视图代码:

from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter

class TestListAPIView(ListAPIView):
   queryset = models.Course.objects.filter(is_delete=False).all()
   serializer_class = serializers.FreeCourseModelSerializer

   # 配置过滤器类, 自定义过滤器类可与自带的共用
   filter_backends = [OrderingFilter, MyFilter]  # MyFilter为自定义过滤器
   # 参与排序的字段: ordering=-score,id
   ordering_fields = ['id', 'score']

前端请求:

http://127.0.0.1:8000/api/test?limit=5