'Search Django Model Returns All Instead Of Filter

I am trying to search my Django model but, cannot return the filter result. I am getting all items in the model.

class singleview(generics.ListCreateAPIView):
    
    
    authentication_classes = []

    permission_classes = []
    search_fields = ['name']
    filter_backends= (filters.SearchFilter,)
    queryset = Product.objects.all()
    serializer_class =ProductSerializer

The Url is:

url(r'^api/dualsearch/$', views.singleview.as_view()),

When searching:

http://localhost:8000/api/singleview/?name=n

I return all items. Could you please help return the results in the filter?



Solution 1:[1]

According the DRF documentation (https://www.django-rest-framework.org/api-guide/filtering/#searchfilter):

By default, the search parameter is named 'search', but this may be overridden with the SEARCH_PARAM setting.

You must use the search parameter instead of name:

http://localhost:8000/api/singleview/?search=n

... and correct the search_field to search_fields property as @WillemVanOnsem says.

EDIT

I add a full working example:

from rest_framework import generics, routers, serializers, viewsets, filters

class SingleView(viewsets.ViewSetMixin, generics.ListCreateAPIView):
    authentication_classes = []

    permission_classes = []
    search_fields = ['name']
    filter_backends= (filters.SearchFilter,)
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

router = routers.DefaultRouter()
router.register(r'products', SingleView)


urlpatterns = [
    path('', include(router.urls)),
    # ...
]

curl http://127.0.0.1:8000/products/?search=n

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1