[Answered ]-Why is my Django rest framework api returning an empty list?

0πŸ‘

βœ…

The problem was the form.

The form as I had was:

class SearchForm(forms.Form):
    query = forms.CharField()

the field here query didn’t match with search in the url. So all I did was change the form to this:

class SearchForm(forms.Form):
    search = forms.CharField()

lessons: the field of the form needs to match with the keywords in the url. πŸ™‚

πŸ‘€chez93

1πŸ‘

Your parameter is search not query, so you check with if 'search' in request.GET. But you make things overcomplicated. You can work with:

class SearchForm(forms.Form):
    search = forms.CharField()


@api_view(['GET'])
def post_search(request):
    form = SearchForm(request.GET)
    if form.is_valid():
        results = Paper.objects.annotate(
            search=SearchVector('abstract', 'title')
        ).filter(search=form.cleaned_data['search'])
        serializer = PaperSerializer(results, many=True)
        return Response(serializer.data)
    return Response({'error': 'invalid search'}, status=400)

Leave a comment