1

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

4
  • is query present in request.GET? Commented Jan 7, 2023 at 23:03
  • @sahasrara62 how do I check this? sorry for my ignorance but im new to web dev. Commented Jan 7, 2023 at 23:12
  • You can add import pdb; pdb,set_trace(), after if request.method == 'GET': and restart application and then hit the end point, in terminal run 'query' in request.GET, if it is False then is root cause of your error Commented Jan 7, 2023 at 23:15
  • 'http://127.0.0.1:8000/api/search/?search=Type' That url does not contain a query arg, so if 'query' in request.GET will be false. Commented Jan 7, 2023 at 23:30

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

I get the error: Bad Request: /api/search/ [07/Jan/2023 23:43:08] "GET /api/search/?search=Type HTTP/1.1" 400 26
@chez93: looks like it never "fires" the view, so something is wrong with your urls.py probably. Did you define a view with the same name? Did you forget to include the urlpatterns somewhere in the "top level" urls.py?
here is my top level url: path('api/', include('restapi.urls')),
Try to hit the endpoint without the slash between the url and the parameter. Like this: http://127.0.0.1:8000/api/search?search=Type
@dsenese I tried bout urls - with slash and without it -- and when I do re.json() I get {'error' : 'invalid search'}
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. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.