gpt4 book ai didi

python - 如何重命名 django rest_framework 的 search_fields 中的字段?

转载 作者:太空宇宙 更新时间:2023-11-03 20:37:44 26 4
gpt4 key购买 nike

我有

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 放入 View 的 search_fields 中:

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

关于python - 如何重命名 django rest_framework 的 search_fields 中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com