在Django的数据表中使用服务器端处理时,如何从db获取部分记录?

时间:2019-02-19 13:18:34

标签: django datatables pagination server-side

我的目标是使用数据表在服务器端处理获取的数据。

我的问题是我无法从db获取部分记录(例如:每个ajax请求为50)。例如,当我给限制50定义每页返回的结果数时,在请求后分页器仅返回10。

要基于已定义记录的页面获取数据,是否缺少某些内容?

我的观点

class ProductSerialNumbersListJSon(LoginRequiredMixin,BaseDatatableView):
# my model
model = ProductSerialNumbers
columns = ['snumber' , 'order','product','registration_date']
order_columns = ['snumber','order','product','registration_date']

def get_initial_queryset(self):
    #fetch the query list from db
    query_list=ProductSerialNumbers.objects.filter(Q(snumber__isnull=True)|Q(order_id__isnull=True)|Q (order_id__finished=0)).order_by("id")
    paginator = Paginator(query_list,50) #50 items per page
    page=int(self.kwargs['page'])

    try:
        result = paginator.page(page)
    except PageNotAnInteger:
        result = paginator.page(1)
    except EmptyPage:
        result = paginator.page(paginator.num_pages)
    product_serials = result.object_list.all().values_list('id', flat=True)
    return ProductSerialNumbers.objects.filter(pk__in=product_serials)

我的网址

url(r'^warehouse_tabledata/(?P<page>\d+)/$',views.ProductSerialNumbersListJSon.as_view(), name='warehouse_list_json'),

我的json结果

 {"recordsTotal": 50, "recordsFiltered": 50, "draw": 0, "data": [["3", "", "test_proion", "2019-01-16"], ["55", "", "test_proion", "2019-01-16"], ["56", "", "test_proion", "2019-01-16"], ["57", "", "test_proion", "2019-01-16"], ["58", "", "test_proion", "2019-01-16"], ["59", "", "test_proion", "2019-01-16"], ["60", "", "test_proion", "2019-01-16"], ["61", "", "test_proion", "2019-01-16"], ["62", "", "test_proion", "2019-01-16"], ["63", "", "test_proion", "2019-01-16"]], "result": "ok"}

1 个答案:

答案 0 :(得分:1)

您必须添加分页才能显示每页有限的结果。 django具有内置的分页器,您也可以在模板中进行分页。 下面的代码来自我的一个较早的项目。忽略“ q”,因为它只是我在项目中使用的搜索查询。

paginator = Paginator(query_list, 10) #10 items per page
page = request.GET.get('page') #getting the page number from GET request
try:
    queryset = paginator.page(page)
except PageNotAnInteger:
    queryset = paginator.page(1)
except EmptyPage:
    queryset = paginator.page(paginator.num_pages)
context={
    "obj":queryset,
    "title":"Latest Posts",
}
return render(request,'index.html',context)

现在在模板中

<div class="pagination">
<span class="step-links">
    {% if obj.has_previous %}
        <a href="?page={{ obj.previous_page_number }}{% if request.GET.q%}&q={{request.GET.q}}{% endif %}">previous</a>
    {% endif %}

    <span class="current">
        Page {{ obj.number }} of {{ obj.paginator.num_pages }}.
    </span>

    {% if obj.has_next %}
        <a href="?page={{ obj.next_page_number }}{% if request.GET.q%}&q={{request.GET.q}}{% endif %}">next</a>

如果需要,您可以在go at line 84 to view full function.上签出该项目