如何重命名Django rest_framework的search_fields中的字段?

时间:2019-07-16 11:27:44

标签: python django django-rest-framework django-filter django-filters

我有

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"

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

像这样自定义搜索过滤器:

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']