【问题标题】:How to enable sorting in DataTables (deferred load)?如何在 DataTables 中启用排序(延迟加载)?
【发布时间】:2016-10-23 18:47:50
【问题描述】:

数据表 1.10.12

排序不适用于我的 DataTables 实现。我使用延迟加载数据。

如何进行排序?

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();

如果我单击列标题中的排序图标,结果不会改变。

截图:

【问题讨论】:

    标签: javascript jquery datatables datatables-1.10


    【解决方案1】:

    尝试在按钮元素之后添加它,我使用它来对我们的数据表进行排序,数据表使用 javascript 覆盖数据库排序

    "aaSorting": [  [1,'desc'],  [2,'desc'], [0,'desc'] ],
    

    【讨论】:

    【解决方案2】:

    对于延迟数据表,排序必须在服务器端执行。 Datatables 插件仅将指令发送到服务器,通知排序顺序 (asc, desc) 和要排序的列的索引。 datatables protocol 为此定义了两个特殊键:order[i][dir]order[i][column]

    下面是一个 Python 函数示例,该函数查找用户单击的列的名称和排序顺序:

    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]']]
    

    然后你可以排序,例如,在从 Django 模型中获取对象时:

    sortable_coll = get_sortable_coll_name(message)
    objects = Model.objects.filter(task=task).order_by(sortable_coll)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      相关资源
      最近更新 更多