Here is my code. I get no errors, and I can see the search button that was added to the browsable API. The problem though is the search does not work. No matter what I type into the search, it just returns every objects.
from rest_framework import status, filters
class JobView(GenericAPIView):
serializer_class = JobSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['name']
def get_queryset(self):
return Job.manager.all()
def get(self, request, format=None):
queryset = self.get_queryset()
if queryset.exists():
serializer = JobSerializer(queryset, many=True)
return Response(serializer.data)
else:
return Response({"Returned empty queryset"}, status=status.HTTP_404_NOT_FOUND)
endpoint
http://localhost:8000/jobs/?search=something
returns the same as
http://localhost:8000/jobs/
No matter what I put in the search string, it returns jobs.
This basically doesn't work because you're trying to do too much. You've written your own get
method which bypasses all the magic of the DRF views. In particular, by not calling GenericAPIView.get_object
, you avoid a line that looks like
queryset = self.filter_queryset(self.get_queryset())
which is where the QuerySet is filtered. This simpler version, practically identical to the one in the SearchFilter docs, should work
from rest_framework import status, filters, generics
class JobView(generics.LisaAPIView):
queryset = Job.manager.all()
serializer_class = JobSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['name']
NOTE based on your question, I am assuming:
that your Job
model has a name
field
that for some reason you've renamed the Job
manager to manager
via a call to models.Manager()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With