Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my Django Rest Framework Search filter not working?

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.

like image 737
benjaminadon Avatar asked Oct 16 '25 02:10

benjaminadon


1 Answers

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:

  1. that your Job model has a name field

  2. that for some reason you've renamed the Job manager to manager via a call to models.Manager()

like image 127
RishiG Avatar answered Oct 18 '25 19:10

RishiG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!