如何获取Page对象中的项目数?

时间:2018-03-22 07:16:07

标签: django django-pagination

我从这里学到了一些关于django分页的知识:https://docs.djangoproject.com/en/2.0/topics/pagination/#page-objects

我想知道如何获取某些Page对象中的项目数。

我想的是这样的:SELECT ROUND(coalesce(SUM(c.ClaimNet), 0), 2) as net, MAX(c.ClaimID), count(c.ClaimID) as claims, MAX(h.TransactionDate) as TransactionDate, 'Resubmission' AS 'Claim Type' FROM Claim c LEFT OUTER JOIN ClaimHeader h on h.HeaderID = c.HeaderPKID INNER JOIN Resubmission r ON r.ClaimID = c.ClaimPKID WHERE h.HeaderType=2 HAVING COUNT(*) > 0 UNION ALL SELECT ROUND(coalesce(SUM(c.ClaimNet), 0), 2) as net, MAX(c.ClaimID), count(c.ClaimID) as claims, MAX(h.TransactionDate) as TransactionDate, 'First Submission' AS 'Claim Type' FROM Claim c LEFT OUTER JOIN ClaimHeader h on h.HeaderID = c.HeaderPKID WHERE ClaimPKID NOT IN ( SELECT ClaimID FROM Resubmission GROUP BY ClaimID ) AND HeaderType=2 HAVING COUNT(*) > 0

但我认为结果可能并不好或不准确。

有没有很好的方法来获得正确的结果?

3 个答案:

答案 0 :(得分:2)

模糊地类似于:

Paginator(query, objects_per_page, current_page_number)

然后将生成的paginator对象传递给模板。

在分页器的初始化中,你想要做类似的事情:

def __init__(self, query, objects_per_page, current_page_number):
    self.total = query.count()

    self.per_page = objects_per_page
    self.current_page_number = current_page_number
    self.lower_limit = objects_per_page * current_page_number
    self.upper_limit = objects_per_page * (current_page_number + 1)

    if self.upper_limit > self.total:
        self.upper_limit = self.total

    self.objects = query[self.lower_limit - 1:self.upper_limit - 1]

然后在模板中你会做这样的事情:

Showing {{paginator.lower_limit}}-{{paginator.upper_limit}} of {{paginator.total}}

我希望能让您大致了解如何干净利落地完成这项任务。

答案 1 :(得分:1)

可能len(page.object_list)最简单。

答案 2 :(得分:1)

在模板中:

{{ page_obj.paginator.count }} # The total number of objects, across all pages
{{ page_obj.paginator.per_page }} # The number of objects every page
{{ page_obj.paginator.num_pages }} # The total number of pages.