在 Django 数据中添加行 ID table

Add row Id in Django data table

我正在使用 django 数据表,来自服务器的数据具有以下格式:

[ ['id_value','data col1','data col2',...]
   .
   .
   .]

我正在尝试为每一行制作 id,如下所示:

'rowId': 1,

但是没用

我的html代码:

<table id="mainDataTable" class="table table-responsive-md table-{{ documentvals.table_type }}">
                        <thead>
                        <tr>
                            {% for field in list_fields %}
                                <th> {{ field }}</th>
                            {% endfor %}
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                        <tfoot>
                        <tr>
                            {% for field in list_fields %}
                                <th> {{ field }}</th>
                            {% endfor %}
                        </tr>
                        </tfoot>
                    </table>
            

还有,我的js代码是:

let _columns= [
    {% for field in list_fields %}
        { "data": '{{ field }}' },
        {% endfor %}
]

$('#mainDataTable').DataTable({
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "columns": _columns,
        "autoWidth": false,
        "responsive": true,
        "aaSorting": [],
        "pageLength": pag,
        "bProcessing": true,
        "bServerSide": true,
        "ajax": {
            "url": mainUrl,
        },
        'rowId': 1,
        "pagingType": "full_numbers",
        destroy: true,
    });

我不想编辑 Django 数据表库。

根据我的理解,我认为您正在尝试给出类似于 S.No 的内容。出于任何目的,以 rowId 的形式发送给您的 table。

可能需要 python 中的 enumerate 来实现此目的,在这种情况下,您可以在 django 模板中使用 forloop 计数器,可用于多种变体,如下所示

仅供参考,以下是如何在 _columns 变量 for js 文件循环

中使用它
let _columns= [
    {% for field in list_fields %}
        { "data": '{{ field }}', "rowId": '{{forloop.counter}}' },
    {% endfor %}
]

同样,它也可以在你的table中使用。

我强烈建议你看看official django templating forloop documentation.