如何在 Django REST 框架中更改 URL 中的默认搜索查询参数?



In Django REST Framework.默认情况下,它在搜索任何内容时在 URL 中使用 -/?search=。 例如 http://127.0.0.1:8000/api/branches/?search=RTGS 并且此网址成功获得结果。 但是我需要将 URL 更改为 http://127.0.0.1:8000/api/branches/autocomplete?q=RTGS

在文档中,https://www.django-rest-framework.org/api-guide/settings/#search_param 给定它是默认设置的。 https://www.django-rest-framework.org/api-guide/settings/#search_paramd 我们可以改变。 我想知道如何。

谢谢

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

urls.py 从 django.urls 导入路径,包括 从。导入视图 从rest_framework导入路由器

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

从文档中:

默认情况下,搜索参数名为'search',但可以使用SEARCH_PARAM设置覆盖。

因此,在您的settings.py中:

REST_FRAMEWORK = {
'SEARCH_PARAM': 'q'
}

编辑

在这里你可以看到实际的代码:

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

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

如果只想更改一个视图中的查询参数键,可以扩展 SearchFilter 并将其添加到视图中filter_backends

class CustomSearchFilter(SearchFilter):
search_param = "q"

class MyListView(ListAPIView):
# ...
filter_backends = [CustomSearchFilter]
# ...

最新更新