DataTables component usage ServerSide

The first to recognize datatables because AdminLTE

AdminLTE is a class-based bootstrap3 background site templates, open source, there are free version. As a web front-end operation and maintenance dog wants to be a good starting point

There is also a nice guy named easyui , but UI product like ancient times, pay attention to the face, or forget

DataTables is a good jq components, in addition to AdminLTE, like in the template sbadmin also seen

Some front-end feeling things are hard to explain way to interact with back-end, including me now in use layuiadmin, and vue-admin I am learning, or my personal position does not open the document?

Not wordy, directly on the dry bar, first look at how to write html and js

<div id="divTable">
   <table id="table" class="table table-bordered" style="width:100%">
    <thead>
      <tr>
        <th>姓名</th>
        <th>账号</th>
        <th>手机</th>
        <th>邮箱</th>
      </tr>
    </thead>
  </table>
</div>
<script>
// datatables 英翻中
var datatableLanguage = {
  "sProcessing": "载入中...",
  "sLengthMenu": "显示 _MENU_ 项结果",
  "sZeroRecords": "没有匹配结果",
  "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
  "sInfoEmpty": "显示第 0 至 0 项结果,共 0 项",
  "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
  "sInfoPostFix": "",
  "sSearch": "搜索:",
  "sUrl": "",
  "sEmptyTable": "没有对应的数据",
  "sLoadingRecords": "载入中...",
  "sInfoThousands": ",",
  "oPaginate": {
    "sFirst": "首页",
    "sPrevious": "上页",
    "sNext": "下页",
    "sLast": "末页"
  },
  "oAria": {
    "sSortAscending": ": 以升序排列此列",
    "sSortDescending": ": 以降序排列此列"
  }
}
// 表格初始化
var table = $("#table").DataTable({
    deferRender: true,
    lengthMenu: [ [10, 25, -1], [10, 25, "所有"] ],
    searchDelay: 500,
    pagingType: "simple_numbers",
    autoWidth: false,
    select: true,
    ordering: false,
    processing: true,
    serverSide: true,
    ajax: "{% url 'table_data_api' %}",
    language: datatableLanguage,
});
</script>

Django backend for example

if request.method == 'GET':
    kwargs = dict(request.GET)
    filter_args = {
        'draw': int(kwargs['draw'][0]),
        'start': int(kwargs['start'][0]),
        'length': int(kwargs['length'][0]),
        'search': kwargs['search[value]'][0]
    }
    return namedtuple('D2N', list(filter_args.keys()))(**filter_args)
raise HttpBadRequest('额,好像不是约定的datatable请求格式')

You can see datatable serverside only need four key parameters

  1. draw: I do not know what to do and what the return pass on the right what
  2. start: starting position
  3. length: the data length (tab)
  4. search: search for content

Get the parameters, you can begin to return to work generated data

# 获取上面datatables的请求参数
datatable_args = get_datatable_args()

# 基础过滤和排序
queryset = User.objects.filter(enable=True, delete=False)

# 处理表格搜索
if datatable_args.search != '':
    queryset = queryset.filter(
        Q(name__contains=datatable_args.search)
        | Q(account__contains=datatable_args.search)
    )

# 返回数据格式
ret = {
    'draw': datatable_args.draw,
    'recordsTotal': queryset.count(),  // 页面上的共有*条数据
}

# 处理数据本体
data = []
if queryset.count() != 0:
    if datatable_args.length == -1:
        # length = -1 为显示所有,不分页
        item_list = queryset
        
    else:
        # 按length要求处理分页
        # Paginator 分页函数的来源是 from django.core.paginator import Paginator
        p = Paginator(queryset, datatable_args.length)
        if datatable_args.start == 0:
            page_num = 1
        else:
            page_num = datatable_args.start / datatable_args.length + 1
        item_list = p.page(page_num).object_list

    # 开始生成表格内容
    for item in item_list:
        data.append(
            [
                item.name,
                item.account,
                item.mobile,
                item.email
            ]
        )
        
# 以datatables可识别格式返回,records开头的两个变量的作用为:
# “共 total_num 条数据,显示 filter_num 条
# ret = {
#     'recordsFiltered': filter_num, 
#     'recordsTotal': total_num,
#     'data': data,
#     'draw': datatable_args.draw,
# }
ret.update(
    **{'recordsFiltered': queryset.count(), 'data': data}
)
return JsonResponse(ret)

Well, get

Guess you like

Origin www.cnblogs.com/tutuye/p/11591896.html