Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
TutajITeraz opened this issue Mar 6, 2024 · 2 comments

Comments

@TutajITeraz
Copy link

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
Copy link

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
Copy link

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants