rest_framework_mongoengine实现搜索

直接只用rest_framework的搜索会不起作用

settings

    'DEFAULT_FILTER_BACKENDS': [
        'rest_framework.filters.SearchFilter',  # 模糊搜索
        # 'django_filters.rest_framework.DjangoFilterBackend'  # 精准搜索(完全匹配)
    ]

view

# 资产类型
class CiTypeViewSet(ModelViewSet):
    queryset = CiType.objects.all()
    serializer_class = CiTypeSerializer
    permission_classes = [
        IsAuthenticated,
        CmdbModelPermissions]  # 注意权限,不然会报错 <class 'AttributeError'> 'QuerySet' object has no attribute 'model'
    search_fields = ['name']  # 模糊搜索的字段域

那么就需要重写filter_backends,经过研究只需要重写filter_queryset就行了,最终view如下

为rest_framework_mongoengine改进view

# 资产类型
class CiTypeViewSet(ModelViewSet):
    queryset = CiType.objects.all()
    serializer_class = CiTypeSerializer
    # filter_backends = [SearchFilter] 自定义搜索类
    permission_classes = [
        IsAuthenticated,
        CmdbModelPermissions]  # 注意权限,不然会报错 <class 'AttributeError'> 'QuerySet' object has no attribute 'model'
    search_fields = ['name']  # 模糊搜索的字段域

    def filter_queryset(self, queryset):  # 兼容mongo搜索,重写filter_queryset
        search = self.request.query_params.get('search')
        # 通过先封装成一个字典再用**运算符解包,完美解决
        if search:
            q = Q()
            for field in self.search_fields:
                zip_field = {field + '__icontains': search}
                q = q | Q(**zip_field)
            queryset = queryset.filter(q)
        return queryset

 

参考文章:https://blog.csdn.net/weixin_42144277/article/details/105839070

posted @ 2022-11-18 15:13  豆浆D  阅读(172)  评论(0编辑  收藏  举报