Django DRF-使用基本搜索过滤器进行多重或搜索

时间:2019-08-28 11:32:37

标签: django django-rest-framework django-rest-viewsets

我正在尝试使用基本的Django过滤器进行多重或搜索。我已经尝试过以下网址,但它们只会返回第一个结果

api / circuit /?search = AB5814765; AB827451; AB0923784

使用逗号也不会返回结果。

是否有任何语法可以显示内置的多个记录或需要做一些自定义的操作,我尝试了几次自定义尝试,但它们也都失败了

尝试执行以下操作时,我会得到404

api / circuit / ref_search / AB5814765 | AB827451 | AB0923784

@action(detail=False, methods=['get'], url_path='ref_search/(?P<refs>[^/.]+)/', permission_classes=[IsAdminUser])
def ref_search(self, request, refs, *args, **kwargs):
    refs = refs.split('|')
    query = Q()
    for x in refs:
        q = Q(circuit__ref_no=x)
        query |= q
    queryset = DeviceCircuitSubnets.objects.filter(query)
    serializer = self.serializer_class(queryset, many=True)
    return Response(data=serializer.data)  

我也尝试过

api / circuit / ref = AB5814765 | AB827451 | AB0923784

def get_queryset(self):
    refs = self.request.query_params.get('ref', None)
    if refs is not None:
        refs = refs.split('|')
        query = Q()
        for x in refs:
            q = Q(status=x)
            query |= q
        queryset = queryset.filter(query)
    return queryset

我的观点:

class SiteCircuitDataROView(viewsets.ReadOnlyModelViewSet):
    queryset = Circuit.objects.all()
    serializer_class = CircuitSerializer
    permission_classes = (IsAdminUser,)
    filter_class = Circuit
    filter_backends = (filters.SearchFilter,)

2 个答案:

答案 0 :(得分:1)

您可以使用__in并致电api/circuit/?refs=AB5814765|AB827451|AB0923784

class SiteCircuitDataROView(viewsets.ReadOnlyModelViewSet):
    queryset = Circuit.objects.all()
    serializer_class = CircuitSerializer
    permission_classes = (IsAdminUser,)
    filter_class = Circuit
    filter_backends = (filters.SearchFilter,)

    @action(detail=False, methods=['get'], url_path='ref_search/', permission_classes=[IsAdminUser])
    def ref_search(self, request, *args, **kwargs):
        refs = self.request.get('refs', '').split('|')
        queryset = DeviceCircuitSubnets.objects.filter(ref__in=refs)
        serializer = self.serializer_class(queryset, many=True)
        return Response(data=serializer.data)

答案 1 :(得分:1)

按如下所示更改视图

class SiteCircuitDataROView(viewsets.ReadOnlyModelViewSet):
    serializer_class = CircuitSerializer
    permission_classes = (IsAdminUser,)

    def get_queryset(self):
        queryset = Circuit.objects.all()
        search = self.request.GET.get('search', '').split(',')
        if search:
           query = Q()
           for term in search:
               query = query | Q(circuit__ref_no__icontains=term)
           queryset = queryset.filter(query)
        return queryset

现在,发送如下网址所示的请求

api/circuit/?search=AB5814765,AB827451,AB0923784