如何在Djangotables2中添加counter列?

2024-06-06 01:05:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用django-tables2在表的第一列上添加一个计数器,但是下面的解决方案只显示#列下的所有0。我应该如何添加一个列,它将有一个对行进行编号的列?在

在表格.py公司名称:

import django_tables2 as tables
from profiles.models import Track
import itertools
counter = itertools.count()

class PlaylistTable(tables.Table):

    priority = tables.Column(verbose_name="#", default=next(counter))

    class Meta:
        model = Track
        attrs = {"class": "paleblue"}
        orderable = False
        fields = ('priority', 'artist', 'title')

我的模板:

^{pr2}$

Tags: djangopyimporttablescounter计数器公司track
3条回答

来自^{}的文档

default (str or callable):

The default value for the column. This can be a value or a callable object [1]. If an object in the data provides None for a column, the default will be used instead.

[1] - The provided callable object must not expect to receive any arguments.

你传递的是next(counter)你传递的是一个看起来是整数的函数的结果。在

您可以定义函数:

def next_count():
    return next(counter)

并且,使用它作为默认值:

^{pr2}$

或者,您可以使用@Sayse注释中提到的lambda函数:

priority = tables.Column(verbose_name="#", default=lambda: next(counter))

根据Jieter的回答,您可以通过以下小修改来处理分页:

import django_tables2 as tables
import itertools

class CountryTable(tables.Table):
    counter = tables.Column(empty_values=(), orderable=False)

    def render_counter(self):
        self.row_counter = getattr(self, 'row_counter',
                                   itertools.count(self.page.start_index()))
        return next(self.row_counter)

即使在第一行之后的页面中,行号也将是全局正确的。注意,在本例中,索引是从1开始的。在

其他答案都在tables.py文件的顶层作用域中有itertools.count实例。这使得计数器在页面加载之间保持不变,只有在服务器重新启动时才会重置计数器。更好的解决方案是将counter作为实例变量添加到表中,如下所示:

import django_tables2 as tables
import itertools

class CountryTable(tables.Table):
    counter = tables.Column(empty_values=(), orderable=False)

    def render_counter(self):
        self.row_counter = getattr(self, 'row_counter', itertools.count())
        return next(self.row_counter)

这将确保每次实例化表时都重置计数器。在

相关问题 更多 >