我有
class ProductSearch(ListAPIView):
queryset = Product.objects.all()
permission_classes = [AllowAny]
serializer_class = ProductSearchSerializer
filter_backends = [SearchFilter]
filter_fields = ['meta_data', 'store__district__id']
但是当我通过api搜索时,我需要输入
"store__district__id": "blabla"
但是我只想代替这个
"district_id": "x"
有人可以帮忙吗?
最佳答案
像这样自定义搜索过滤器:
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
并将其放在您的
filter_backends
中,然后将district_id
放入视图的search_fields
中:class ProductSearch(ListAPIView):
queryset = Product.objects.all()
permission_classes = [AllowAny]
serializer_class = ProductSearchSerializer
filter_backends = [ProductSearchFilter]
search_fields = ['meta_data', 'district_id']