Reputation: 5634
DataTables 1.10.12
Sorting doesn't work for my DataTables implementation. I use deferred loading of data.
How to make sorting work?
var hash_table = $('#hash_table');
var data_table = hash_table.DataTable({
processing: true,
serverSide: true,
deferLoading: 100,
ordering: true,
order: [[ 0, 'asc' ]],
ajax: {
url: 'get_hashes/',
type: 'POST',
},
columns: [
{'title': 'BRC ID', 'data': 'brc_id'},
{'title': 'HASH', 'data': 'hash'}
],
dom: 'Brtip',
buttons: [
{
extend: 'excel',
title: 'report',
text: 'Export',
extension: '.xlsx'
}
]
});
data_table.draw();
The result doesn't change if I click on the sorting icons in the columns header.
Upvotes: 3
Views: 1270
Reputation: 5634
For the deferred DataTables, the sorting must be executed on the server side.
Datatables plugin only sends the instructions to the server notifying the sorting order (asc, desc
) and the index of a column to sort. The datatables protocol defines two special keys for this: order[i][dir]
and order[i][column]
.
Below is an example of Python function that finds a name of the column on which user clicked and sorting order:
def get_sortable_coll_name(message):
colls = {
'1': 'date',
'3': 'project',
'4': 'project_id',
'5': 'total_matches',
'6': 'successful_matches',
'7': 'failed_matches',
'8': 'status'
}
if message['order[0][dir]'] == 'asc':
return '-' + colls[message['order[0][column]']]
else:
return colls[message['order[0][column]']]
Then you can sort, for example, during getting objects from Django models:
sortable_coll = get_sortable_coll_name(message)
objects = Model.objects.filter(task=task).order_by(sortable_coll)
Upvotes: 1
Reputation: 312
try adding this after the buttons element, I use this to sort our datatables, datatables override db sorting with javascript
"aaSorting": [ [1,'desc'], [2,'desc'], [0,'desc'] ],
Upvotes: 1