views.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" OR区" Pune"
如果我搜索http://api/tool/?crops=guava,banana,你可以帮我解决一下我的代码变化吗?
或者http:../ tool /?district = Nasik,Pune
给我正确的输出?
答案 0 :(得分:2)
我建议您查看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的调用应产生所需的行为。 我无法测试它现在是否有效,但这应该会引导你走向正确的方向。