Home > OS >  Why is my Django rest framework api returning an empty list?
Why is my Django rest framework api returning an empty list?

Time:01-08

Hello I am working on an Django Rest Framework api and one of the views is returning an empty list.

here's my view:

@api_view(['GET'])
def post_search(request):
    form = SearchForm()
    query = None
    results = []
    if request.method == 'GET':
        if 'query' in request.GET:
            form = SearchForm(request.GET)
            if form.is_valid():
                query = form.cleaned_data['query']
                results = Paper.objects.annotate(
                    search=SearchVector('abstract', 'title'),).filter(search=query)
        serializer = PaperSerializer(results, many=True)

        return Response(serializer.data)

here is the form:

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

and here are my urls:

path('search/', views.post_search, name='post_search'),

So on the shell I ran:

Paper.objects.annotate(search=SearchVector('abstract', 'title'),).filter(search='Type')

and I got the results I wanted but when do this:

import requests
url = 'http://127.0.0.1:8000/api/search/?search=Type'
re = requests.get(url)
re.json # -> []
# or
import json
json.loads(re) # ->raise TypeError(f'the JSON object must be str, # bytes or bytearray, '
#TypeError: the JSON object must be str, bytes or bytearray, not Response

Any help will be appreciated; thanks

CodePudding user response:

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)

CodePudding user response:

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. :)

  • Related