3

视图.py

from __future__ import unicode_literals

from rest_framework_mongoengine.viewsets import ModelViewSet as MongoModelViewSet

from app.serializers import *

from rest_framework_mongoengine.generics import * 

from rest_framework import filters    


def index_view(request):
    context = {}
    return TemplateResponse(request, 'index.html', context)


class ToolViewSet(MongoModelViewSet):
    serializer_class = ToolSerializer
    my_filter_fields = ('crop', 'district','taluka','circle','year',) 

    def get_kwargs_for_filtering(self):
        filtering_kwargs = {} 

        for field in  self.my_filter_fields: # iterate over the filter fields
            field_value = self.request.query_params.get(field) # get the value of a field from request query parameter
            if field_value: 
                filtering_kwargs[field] = field_value
        return filtering_kwargs 

    def get_queryset(self):
        queryset = Tool.objects.all() 
        filtering_kwargs = self.get_kwargs_for_filtering() # get the fields with values for filtering 
        if filtering_kwargs:
            queryset = Tool.objects.filter(**filtering_kwargs) # filter the queryset based on 'filtering_kwargs'
        return queryset

这是我的代码。

它可以准确过滤我们想要搜索的内容。

例如:http://api/tool/?district=Nasik&crop=banana

但是,它不适用于列表文件,例如: http://api/tool/?district=Nasik&district=Pune 这给出了输出:[](空)

如何让这个过滤器工作以获得所有区“Nasik”或区“Pune”

如果我搜索http://api/tool/?crops=guava,banana 或 http:../tool/?district=Nasik,Pune
给我正确的信息,你能帮我更改我的代码以获取数据吗输出?

4

1 回答 1

3

我建议看一下django-rest-framework-filters。然后,您可以使用__in查询参数中的内容...

但是如果你想继续你的方法,我会在你的get_kwargs_for_filtering方法中添加逻辑,如下所示:

def get_kwargs_for_filtering(self):
    filtering_kwargs = {} 

    for field in  self.my_filter_fields: # iterate over the filter fields
        field_value = self.request.query_params.get(field) # get the value of a field from request query parameter
        if field_value: 
            if ',' in field_value: # put your queryParams into an array and use the built-in django filter method '__in'
                filtering_kwargs[field + '__in'] = field_value.split(',')
            else:
                filtering_kwargs[field] = field_value
    return filtering_kwargs

有了这个,对http://api/tool/?crops=guava,banana的调用应该会产生所需的行为。我现在无法测试它是否有效,但这应该会引导您走向正确的方向。

于 2017-01-03T08:19:55.060 回答