使用“ SearchFilter”时,尝试搜索时出现错误

时间:2019-06-17 13:40:25

标签: python django django-rest-framework

当我在api中使用搜索功能时,出现错误消息“无法将关键字'q / c'解析为字段。选择为'XXX'”。q或c取决于我所在的api页面。我假定的“ c”代表我的选择之一,而我假定的“ q”代表问题一。

from rest_framework import generics  
from . serializers import QuestionSerializer, ChoiceSerializer  
from django_filters.rest_framework import DjangoFilterBackend  
from rest_framework.filters import OrderingFilter, SearchFilter


from polls.models import Choice, Question


# need to create a view for each serializer class QuestionList(generics.ListAPIView):
    serializer_class = QuestionSerializer  # set the serializer
    queryset = Question.objects.all()  # set the query set to all the objects of that view
    filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter)  # allows for filters
    filter_fields = {'id': ['gte', 'lte', 'exact'], 'pub_date': ['gte', 'lte']}
    ordering_fields = ('id', 'question_text', 'pub_date')
    search_fields = 'question_text'


class ChoiceList(generics.ListAPIView):
    serializer_class = ChoiceSerializer
    queryset = Choice.objects.all()
    filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter)
    # trying to do greater than or less than filter fields stuff
    filter_fields = {'id': ['gte', 'lte', 'exact'], 'votes': ['gte', 'lte', 'exact']}
    ordering_fields = ('id', 'votes', 'choice_text', 'question',)
    search_fields = 'choice_text'

Here's the error page I get when i try to use search

1 个答案:

答案 0 :(得分:1)

documentation说:

  

search_fields属性应该是模型上文本类型字段的名称列表

您正在为两个search_fields变量分配一个字符串。将此更改为列表或元组,如下所示:

search_fields = ('question_text',)
search_fields = ('choice_text',)