動態化 DRF 的 search_fields,時而搜索所有列,時而搜索指定列

The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin’s search functionality.

When in use, the browsable API will include a SearchFilter control:

在這裏插入圖片描述

The SearchFilter class will only be applied if the view has a search_fields attribute set. The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField.

from rest_framework import filters

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['username', 'email']

This will allow the client to filter the items in the list by making queries such as:

http://example.com/api/users?search=russell

You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:

search_fields = ['username', 'email', 'profile__profession']

By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.

The search behavior may be restricted by prepending various characters to the search_fields.

'^' Starts-with search.
'=' Exact matches.
'@' Full-text search. (Currently only supported Django's PostgreSQL backend.)
'$' Regex search.

For example:

search_fields = ['=username', '=email']

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

To dynamically change search fields based on request content, it’s possible to subclass the SearchFilter and override the get_search_fields() function. For example, the following subclass will only search on title if the query parameter title_only is in the request:

from rest_framework import filters

class CustomSearchFilter(filters.SearchFilter):     -------Bingo
    def get_search_fields(self, view, request):
        if request.query_params.get('title_only'):
            return ['title']
        return super(CustomSearchFilter, self).get_search_fields(view, request)

from: https://www.django-rest-framework.org/api-guide/filtering/#searchfilter

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章