izimobil / django-rest-framework-datatables

Seamless integration between Django REST framework and Datatables.
http://django-rest-framework-datatables.readthedocs.io/en/latest/
MIT License
394 stars 88 forks source link

Datatables incorrectly calculates the number of pages with custom filter_backend #144

Open TutajITeraz opened 7 months ago

TutajITeraz commented 7 months ago

Hi, First of all, thank you for creating this framework. It saved me a lot of time integrating datatables with django, especially since I have only been working in diango for 6 months!

The problem I encountered, which is not standardly supported by datatables, is that I needed to create a filter for two numeric values on one column ( less/greater than specified ) .

After reading the documentation: https://django-rest-framework-datatables.readthedocs.io/en/latest/tutorial.html#filtering

I decided to create my own filter backend.

The problem I've encountered is that datatables now incorrectly calculates the number of pages, as if it didn't take into account that my filter was reducing the number of results

my ViewSet:

class ContentViewSet(viewsets.ModelViewSet):
    queryset = Content.objects.all().order_by('manuscript')
    serializer_class = ContentSerializer

    filter_backends = [CustomDatatablesFilterBackend]
    filterset_class = ContentGlobalFilter

And my CustomDatatablesFilterBackend:

class CustomDatatablesFilterBackend(DatatablesFilterBackend):

    def filter_queryset(self, request, queryset, view):
        queryset = super().filter_queryset(request, queryset, view)

        where_min = request.query_params.get('where_min')
        where_max = request.query_params.get('where_max')

        if where_min is not None:
            queryset = queryset.filter(where_in_ms_from__gte=where_min)

        if where_max is not None:
            queryset = queryset.filter(where_in_ms_from__lte=where_max)

        return queryset
Intellbg commented 2 months ago

have some sort of same problem here. Im appending params in the Ajax query. They do filter the data but are not being recognized by the pagination classes. Thinking because of are not send in the col[] format

StevenMapes commented 1 month ago

What I tend to do is to perform that filter in the view/viewset rather than in the filter, that way it's already been applied to the queryset before the queryset is passed into the filter

If you do that you should find it resolves your issue

The method you want to overloads will be either get_queryset, which is where I tend to do it, or filter_queryset.

To help you decide have a look at the CFRF website - https://www.cdrf.co/