视图.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
给我正确的信息,你能帮我更改我的代码以获取数据吗输出?