“如何在'django rest_framework'中添加搜索过滤器”

时间:2019-07-19 03:12:23

标签: django-rest-framework

“我要在我的数据库中进行搜索,例如www.127.0.0.1:8000 / q?lno = a12345或lnocontain = --- 2345包含最后2345个”“

sample_db

  1. lno = a12345
  2. lno = b23345

    .........

    ... 等等

model.py

    lno = models.CharField(max_length=8, unique=True)

view.py

    class GetPostOneL(ListCreateAPIView):
        serializer_class = OneLSerializers
        permission_classes = (IsAuthenticated,)
        pagination_class = CustomPagination
        authentication_classes = (TokenAuthentication,)


        def get_queryset(self):
            reseller = self.request.user
            if reseller.is_authenticated:
                return OneL.objects.filter(reseller=reseller)
            return OneL.objects.none()

        def get(self, request):
            onesales = self.get_queryset()
            paginate_queryset = self.paginate_queryset(onesales)
            serializer = self.serializer_class(paginate_queryset, many=True)
            return self.get_paginated_response(serializer.data)```

1 个答案:

答案 0 :(得分:0)

您可以使用以下更一般的搜索范围:

http://127.0.0.1:8000/?search=a12345

内在逻辑:

class GetPostOneL(ListCreateAPIView):
    ...

    def get(self, request):
        onesales = self.get_queryset()
        search_query = request.GET.get('search', False)

        if search_query:
            onesales = onesales.filter(lno__icontains=search_query)

        paginate_queryset = self.paginate_queryset(onesales)
        serializer = self.serializer_class(paginate_queryset, many=True)
        return self.get_paginated_response(serializer.data)

如果您想通过单词结尾显式搜索,可以查看:

https://docs.djangoproject.com/en/2.2/ref/models/querysets/#endswith