Django 2.2+调用rest api,根据ID列表进行过滤

时间:2019-09-02 08:17:29

标签: django django-rest-framework

在django rest框架中,如何使用in运算符对ID列表进行过滤以获取ViewSet的结果?

几年前(Call django rest API with list of model ids)找到了一个相同问题的解决方案,但是该解决方案不再起作用,调整参数名称更改后的视图集只会返回:

HTTP 400 Bad Request
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "ids": [
        "Enter a number."
    ]
}

我做错了什么吗?我目前对实现的尝试如下:

class ListFilter(django_filters.Filter):
    def filter(self, qs, value):
        if value not in (None, ''):
            integers = [int(v) for v in value.split(',')]
            return qs.filter(**{'%s__%s' % (self.name, self.lookup_type): integers})
        return qs


class MarkerFilter(django_filters.FilterSet):
    ids = django_filters.NumberFilter(field_name="id", lookup_expr='in')

    class Meta:
        model = Marker
        fields = ['ids']


class MarkerViewSet(viewsets.ModelViewSet):
    queryset = Marker.objects.all()
    serializer_class = MarkerSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_class = MarkerFilter

1 个答案:

答案 0 :(得分:0)

此处更新了可解决此问题的代码。上一个问题的公认答案有一些错误,并且一些参数名称已更改,并将这些更改反映在此处,id列表过滤的工作方式如下:

class ListFilter(django_filters.Filter):
    def filter(self, qs, value):
        if value not in (None, ''):
            integers = [int(v) for v in value.split(',')]
            return qs.filter(**{'%s__%s' % (self.field_name, self.lookup_expr): integers})
        return qs


class MarkerFilter(django_filters.FilterSet):
    ids = ListFilter(field_name="id", lookup_expr='in')

    class Meta:
        model = Marker
        fields = ['ids']


class MarkerViewSet(viewsets.ModelViewSet):
    queryset = Marker.objects.all()
    serializer_class = MarkerSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_class = MarkerFilter