在 Django 数据表中添加行 ID

问题描述

我正在使用 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 的形式发送到您的桌子上。

可能需要python中的enumerate之类的东西来实现这一点,在这种情况下,您可以在django模板中使用forloop计数器,有多种变体,如下所示 enter image description here

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

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

同样,它也可以用在您的表中。

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