如何在django-tables2中添加计数器列?

bay*_*man 6 python django django-tables2

我正在尝试使用django-tables2在表的第一列上添加一个计数器,但是下面的解决方案仅在#列下显示全0。我应该如何添加一列,该列将为行编号?

table.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')
Run Code Online (Sandbox Code Playgroud)

我的模板:

{% render_table table %}
Run Code Online (Sandbox Code Playgroud)

Jie*_*ter 5

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

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)
Run Code Online (Sandbox Code Playgroud)

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