request from client side comes in array, how to handle it with Django rest framework filter

199 views Asked by At

As I mentioned in heading, client side filter request comes in this pattern from tabulator data table to rest framework back end.

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

i have tried this way but it is not working

    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
2

There are 2 answers

1
vishnu sandhireddy On

You can try looping through all the request get variables and extract data

    for key in request.GET:
        print(key)
        value = request.GET[key]
        print(value)
0
Oli Folkerd On

Tabulator sends the ajax request in this way because it is the standard way of representing array data in a PHP request.

If you want to structure the request differently you can use the ajaxURLGenerator function to structure the request parameters in any way you like:

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
    },
});

For full details checkout the Ajax Documentation