[Django]-How can I rename field in search_fields of django rest_framework?

2👍

Customize a search filter like this:

from rest_framework import filters

class ProductSearchFilter(filters.SearchFilter):
    def get_search_fields(self, view, request):
        fields = super(CustomSearchFilter, self).get_search_fields(view, request)
        if 'district_id' in fields:
            fields['store__district__id'] = fields.pop('district_id')
        return fields

and place it in your filter_backends and put district_id in search_fields of the view:

class ProductSearch(ListAPIView):
    queryset = Product.objects.all()
    permission_classes = [AllowAny]
    serializer_class = ProductSearchSerializer
    filter_backends = [ProductSearchFilter]
    search_fields = ['meta_data', 'district_id']

Leave a comment