Search code examples
python-3.xrestdjango-modelsdjango-rest-frameworkdjango-2.2

How to change the default search query parameter in URL in Django REST framework?


In Django REST Framework. By default it uses - /?search= in URL while searching for anything. For Example http://127.0.0.1:8000/api/branches/?search=RTGS And this url successfully getting the result. But I need to change the URL to http://127.0.0.1:8000/api/branches/autocomplete?q=RTGS

In the documentation, https://www.django-rest-framework.org/api-guide/settings/#search_param It is given that it is set by default. https://www.django-rest-framework.org/api-guide/settings/#search_paramd we can change. I am wondering how.

Thanks

https://www.django-rest-framework.org/api-guide/settings/#search_param

urls.py from django.urls import path, include from . import views from rest_framework import routers

router = routers.DefaultRouter()
# router.register('bank', views.BankView)
router.register('branches/autocomplete', views.BankDetailView)
# router.register('branches/list', views.BankAPIListView)



urlpatterns = [
    path('api/', include(router.urls)),

]

views.py

from django.shortcuts import render, redirect
from rest_framework import viewsets
from .models import Branches
from .serializers import BranchesSerializer
from rest_framework import filters
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import PageNumberPagination  
# from django_filters.rest_framework import DjangoFilterBackend





class BankDetailView(viewsets.ModelViewSet):
    queryset = Branches.objects.all()
    serializer_class = BranchesSerializer
    filter_backends = [filters.SearchFilter, OrderingFilter]
    # Partial Search with the field in branch
    search_fields = ['^branch']
    # Ordering Filter field by ifsc in ascending order
    # filter_backends = [DjangoFilterBackend]
    # filterset_fields = ['ifsc']

serializers.py

from rest_framework import serializers
from .models import Branches

class BranchesSerializer(serializers.HyperlinkedModelSerializer):
    class Meta :
        model = Branches
        fields = ['url' ,'ifsc', 'bank_id', 'branch', 'address', 'city', 
'district', 'state']

http://127.0.0.1:8000/api/branches/autocomplete?q=RTGS&limit=3&offset=0


Solution

  • From the docs:

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

    Thus, in your settings.py:

    REST_FRAMEWORK = {
        'SEARCH_PARAM': 'q'
    }
    

    EDIT:

    Here you can see the actual code:

    Settings: https://github.com/encode/django-rest-framework/blob/master/rest_framework/settings.py#L68

    Filters: https://github.com/encode/django-rest-framework/blob/master/rest_framework/filters.py#L42