首页 > 解决方案 > 来自客户端的请求以数组形式出现,如何使用 Django REST 框架过滤器处理它

问题描述

正如我在标题中提到的,客户端过滤器请求以这种模式从制表数据表到休息框架后端。

/?page=1&size=10&filters[0][field]=q&filters[0][type]=like&filters[0][value]=something

我已经尝试过这种方式,但它不起作用

    class MemberListSerializerView(generics.ListAPIView):
        model = Membership
        serializer_class = MemberSerializer
        pagination_class = CustomPagination
    
        def get_queryset(self):
            queryset = Membership.objects.members()
            query = self.request.query_params.get('filters[value][0]', None)
            if query is not None:
                queryset = queryset.filter(
                Q(user__username__icontains=query) |
                Q(user__first_name__icontains=query) |
                Q(user__last_name__icontains=query)
                )
            return queryset

标签: djangodjango-rest-frameworktabulator

解决方案


Tabulator 以这种方式发送 ajax 请求,因为它是在 PHP 请求中表示数组数据的标准方式。

如果您想以不同的方式构造请求,您可以使用ajaxURLGenerator函数以您喜欢的任何方式构造请求参数:

var table = new Tabulator("#example-table", {
    ajaxURLGenerator:function(url, config, params){
        //url - the url from the ajaxURL property or setData function
        //config - the request config object from the ajaxConfig property
        //params - the params object from the ajaxParams property, this will also include any pagination, filter and sorting properties based on table setup

        //return request url
        return url + "?params=" + encodeURI(JSON.stringify(params)); //encode parameters as a json object
    },
});

有关完整的详细信息,请查看Ajax 文档


推荐阅读