I want to do a search function with django-rest-framework
this is what I done:
views.py:
I add this :
queryset = Site.objects.all()
serializer_class = SiteSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('name',)
But, when I visit htttp:127.0.0.1/api/v3/vgroup/?search=bob
it give me this error :
The right way to use a search filter is
class TrainingApiView(BListCreateAPIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAdminUser,)
queryset = Training.objects.all()
serializer_class = TrainingSerializer
filter_backends = (OrderingFilter, SearchFilter,)
search_fields = ["training_type", ]
If you are doing it like above then you are doing it RIGHT. You may be thinking about why my endpoint returns all objects instead of a few filtered items? It is because you are trying it with search_fields in postman params.
For example, in my case, training_type
is my search field and if I write my endpoint as below (That is the wrong way)
{{localhost}}/trainings/?training_type=PREMIUM
That is the WRONG WAY to hit SearchFilter for Django API and you will result in having all results from queryset
.
The CORRECT WAY is to use search
instead of search fields mentioned on search_fields = ["training_type", ]
Here is how you should try it the correct way and it will bring exact results
{{localhost}}/trainings/?search=PREMIUM
In short search field is the correct keyword to try query params.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.