使用ListView计算对象

时间:2014-09-17 02:28:56

标签: python django django-templates

我在模板中尝试返回计数寄存器。 我使用ListView。我需要Sale的返回计数寄存器。

我试试

#models.py
class Sale(models.Model):
    customer = models.ForeignKey(Customer)
...
    def __unicode__(self):
        return unicode(self.date_sale)

...
    @property
    def get_counter(self):
        return Sale.objects.count()

#views.py
class SaleList(ListView):
    template_name = 'sale_list.html'
    model = Sale
    context_object = 'sale_list'
    paginate_by = 10

#sale_list.html
{{ sale.get_counter }}

但不行。

如何退回销售计数寄存器?

3 个答案:

答案 0 :(得分:4)

此问题的更好解决方案是使用:

{{ page_obj.paginator.count }}

这样可以避免再次访问数据库以获取计数,这已经在page_obj中提供了。

答案 1 :(得分:2)

尝试

class SaleList(ListView):
    template_name = 'sale_list.html'
    model = Sale
    context_object = 'sale_list'
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(SaleList, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context

如果模板

{{ count }}

答案 2 :(得分:2)

您不需要get_counter功能,甚至不会覆盖get_context功能。

ListView将使用object_list(或者在您的情况下为sales_list)调用模板,这是一个查询集,因此您只需要直接从count()函数访问{{ sales_list.count }} 模板。

因此,只需在模板上使用以下内容:

{{1}}