在 Django REST 框架中。默认情况下,它在搜索任何内容时在 URL 中使用 -/?search= 。 例如http://127.0.0.1:8000/api/branches/?search=RTGS 并且这个url成功得到结果。 但我需要将 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
url.py from django.urls 导入路径,包括 从 。导入 View 从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)),
]
View .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']
序列化器.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
最佳答案
来自the docs :
By default, the search parameter is named
'search'
, but this may be overridden with theSEARCH_PARAM
setting.
因此,在您的 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
关于python-3.x - 如何更改 Django REST 框架中 URL 中的默认搜索查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57705380/