2

I try to use datatables :server-side processing

I have a view :

class DataList(generics.ListAPIView):
    queryset = Data.objects.all()
    serializer_class = DataSerializer
 

And my html :

$(document).ready(function() {
   $('#example').dataTable( {

        "processing": true,   
        /* serverSide:true  */        
        "deferRender": true,           
        "iDisplayLength": 25,
        "paging": true,
        ajax: {
         url: 'http://127.0.0.1:8000/api/datas/',
         dataSrc: ''
        },
       columns: [
            { "data": "id"},
            { "data": "name"},
            { "data": "update_time"},
            { "data": "description"},
        ]
   });

});

This works good.

And then I comment out the serverSide:true :

$(document).ready(function() {
   $('#example').dataTable( {

        "processing": true,   
        "serverSide": true,        
        "deferRender": true,           
        "iDisplayLength": 25,
        "paging": true,
        ajax: {
         url: 'http://127.0.0.1:8000/api/datas/',
         dataSrc: ''
        },
       columns: [
            { "data": "id"},
            { "data": "name"},
            { "data": "update_time"},
            { "data": "description"},
        ]
   });

});

The paginator and search and ordering not work anymore
It seems like it query all data.

I see the datatable example is with php.
I want to intergrate datatable with django rest framework ,What else should I set ??

2
  • why do you want to hide that serverSide : true ? and clear you achieved using PHP Commented Feb 20, 2016 at 6:06
  • My english express not that well ,I edit the description. Commented Feb 20, 2016 at 6:19

2 Answers 2

3

First, read some documentation on server-side processing of datatable: https://datatables.net/manual/server-side. It will tell you what datatable sends to the back-end and what it wants back. Just provide those parameters needed.

Then let me show you some code from my works. It is not the full example, but you will know what to pass back to the datatable() function.

Some consts:

import json


DEFAULT_START_POSITION = 0
DEFAULT_PAGE_SIZE = 10
DEFAULT_SORTING_COLUMN_INDEX = 1
DEFAULT_SORTING_METHOD = 'asc'

#constants for querying
ORDER_DICT = {
    0: 'field1',
    1: 'field2',
}

ORDER_BY = {
    'desc': '-',
    'asc': ''
}

QUERY_FIELDS = ['field1', 'field2']

The main part of the Python code:

def get_sorting(self, request_values):
    return int(request_values.get('iSortCol_0', self.DEFAULT_SORTING_COLUMN_INDEX)),\
           request_values.get('sSortDir_0', self.DEFAULT_SORTING_METHOD).lower()

def get_paging(self, request_values):
    return int(request_values.get('iDisplayStart', self.DEFAULT_START_POSITION)),\
               int(request_values.get('iDisplayLength', self.DEFAULT_PAGE_SIZE))

def render_records(self, current_page_members, query):
    # list to be returned for aaData
    records = []
    # ... do something to put data in the list and return
    return records

def get(self, request):
    # ... receive the request
    # paging
    start, page_size = self.get_paging(request_values)
    # sorting
    sort_column, sort_by = self.get_sorting(request_values)

    # research query
    query = request_values.get('sSearch', '')  # get search term from datatable request
    query_combined = self.get_combined_query(query)

    all_records, filter_count, current_page_records = \
        self.get_member_list(request_values, company_id, query_combined, sort_by, sort_column, start, page_size)

    # json dict to be returned
    records = {
        'iTotalRecords': all_records.count(),    # The total count of records in your database, if query exist, it is the count of filtered records
        'sEcho': request_values.get('sEcho', '0'),    # Represents the rendering count of datatable
        'aaData': [],    # Main data to be rendered in table
    }

    # if no query, all records returned
    records.update({'iTotalDisplayRecords': filter_count if query else records['iTotalRecords']})

    # update aaData list for records
    records['aaData'].extend(self.render_records(current_page_records, query))

    return HttpResponse(json.dumps(records), content_type='application/json')

Please note again, this is not a complete example, you should extend it to your own requirements.

Sign up to request clarification or add additional context in comments.

4 Comments

Where should I place the code?? views.py? serializers.py?
@user2492364 Views, datatable is making GET Requests so u should handle it
This is a custom view and has nothing to do with Django Rest Framework.
This provides a good outline, but I'm having trouble figuring out how to filter the database table by the search term.
0

On your view you are returning ALL the elements in your queryset.

You could slice the results with the values given on the ajax request. Datatables provides the 'start' and 'length' values on the ajax request which you could use to get the correct set to return for the pagination. For example:

start = int(request.POST.get('start', 0))
end = int(request.POST.get('length', 20))

queryset = Data.objects.filter()
queryset = queryset[start:start+end]

Note that for the pagination to work properly, Datatables expects other values for server-side processing , such as recordsTotal and recordsFiltered

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.