Django Server Side set-up for pagination with Datatable

Viewed 224

I am using Django for backend, and I am using Datatable library to display a large number of records ( approx 1 million records ). I am trying to set up datatable in such a way that every time 25 records are being fetched from the backend and when the user clicks on the next page button, another ajax call gets the next 25 records and so on.

But I am having a trouble setting these up.

My DataTable initialisation :

$("#company-table").DataTable({
      "processing": true,
      "serverSide": true,
      "bDestroy": true,
      ajax: {
        type: "POST",
        url: "/get_results/",
        headers: {
          "X-CSRFToken": getCookie("csrftoken"),
        },
        data: {
          ...other data params...
          page:$("#company-table").DataTable().page()
        },
      },
      columns: [
        ...populating columns...
      ],
    });

And my views.py looks like this ( It is completely wrong as far as I know ) :

    #filtered_queryset contains all the records.

    paginator = Paginator(filtered_queryset, 25) # Show 25 contacts per page.
    page_number = request.POST.get('page')
    start = request.POST.get('start')
    length = request.POST.get('length')
    page_obj = paginator.get_page(page_number)
    data = list(page_obj.object_list.values())
    return_data = {"data": data}      
    json_data = json.dumps(return_data,indent=4, sort_keys=True, default=str)
    return HttpResponse (json_data, content_type = "application/json")

Can anyone help me? Or just nudge me in the right direction?

1 Answers
Related