如何在Django应用中实现数据表服务器端分页

时间:2019-05-31 13:35:46

标签: django datatables pagination

我的django项目需要服务器端分页+单独的列搜索。可悲的是我无法实现分页。

我在工作示例中进行了大量搜索,但未找到任何示例。我想自己实现服务器端api,有一些django应用程序,但它们似乎不再被维护了。以下是我的数据表代码+ Django视图。这里有人可以给我一些建议吗?

var table = $('#mainTable').DataTable({
        dom: 'Bfrtip',
        responsive: true,
        serverSide: true,
        processing: true,
        pageLength: 25,
        buttons: [
            'csv', 'print',
            {
                extend: 'colvis',
                text: 'Spalten filtern',
                columns: ':not(.noVis)'
            },
        ],
        ajax: {
            url: '/akquise/mainTableData',
            dataSrc: function ( json ) {
                return json;
           }
        },
        columnDefs: [
            { targets: [0,1,2,3,4,5,6,7,8,9], orderable: false},
            { targets: 0, className: "leadID", searchable: false },
            { targets: 3, className: "firmenname" },
        ],
        columns: [
            { data: "leadID",
                render: function ( data, type, row, meta ) {
                    button = '<a role="button" class="btn btn-secondary" target="_blank" href="details?leadID='+data+'"><i class="fas fa-search"></a>';
                    return button
                }
            },
            { data: "leadID"},
            { data: "status",
                render: function ( data ) {
                    if(data == "Lead"){
                        return "<span class='badge badge-primary'>"+data+"</span>";
                    }
                    if(data == "Kunde"){
                        return "<span class='badge badge-info'>"+data+"</span>";
                    }
                    if(data == "Akquise"){
                        return "<span class='badge badge-warning'>"+data+"</span>";
                    }
                    if(data == "Lieferant"){
                        return "<span class='badge badge-success'>"+data+"</span>";
                    }
                    if(data == "Gesperrt"){
                        return "<span class='badge badge-danger'>"+data+"</span>";
                    }
                }
            },
            { data: "firmenname" },
            { data: "branche" },
            { data: "plz" },
            { data: "ort" },
            { data: "strasse" },
            { data: "telefon" },
            { data: "email" }
        ],
        language: {
                    "url": "//cdn.datatables.net/plug-ins/1.10.19/i18n/German.json",
                    "decimal": ",",
                }
    })

def mainTableData(request):
    search_values = []
    fields = ['leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email']
    for i in range(1, 10):
        value = request.GET.get('columns['+str(i)+'][search][value]')
        search_values.append(value)

    allLeads = Lead.objects.filter(reduce(AND, (Q(**{fields[i]+'__icontains': value} ) for i, value in enumerate(search_values)))).values('leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email')
    allLeads_list = list(allLeads)


    return JsonResponse(allLeads_list, safe=False)

1 个答案:

答案 0 :(得分:0)

首先,您应该添加:

from django.core.paginator import Paginator

这是服务器端分页的内置功能。 试试这个:

def mainTableData(request):
    search_values = []
    fields = ['leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email']
    for i in range(1, 10):
        value = request.GET.get('columns['+str(i)+'][search][value]')
        search_values.append(value)

    allLeads = Lead.objects.filter(reduce(AND, (Q(**{fields[i]+'__icontains': value} ) for i, value in enumerate(search_values)))).values('leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email')

    # Add paginator
    paginator = Paginator(allLeads, request.GET.get('page_length', 25)) # Show 25 contacts per page

    # Add option to read page
    page = request.GET.get('page')  # Add option in ajax or somewhere 
    allLeads_list = paginator.get_page(page) # Return objects list you can make json from this or list

    return JsonResponse(allLeads_list, safe=False)

我添加了这一行,您可以在这里详细了解此内容(https://docs.djangoproject.com/en/2.2/topics/pagination/):

 # Add paginator
 paginator = Paginator(allLeads, request.GET.get('page_length', 25)) # Show 25 contacts per page

 # Add option to read page
 page = request.GET.get('page')  # Add option in ajax or somewhere 
 allLeads_list = paginator.get_page(page) # Return objects list you can make