首页 > 解决方案 > Python,Django:如何将检查的表行放入列表中?

问题描述

晚上好,

我希望有人知道我将表中的所有检查行放入多维列表(提交后)的问题的答案?

我知道我可以做这样的事情来获取 - 例如 - 所有检查的 id 到一个列表中:

模板:

<form action="" method="post">
    {% csrf_token %}

    <div class="table-wrapper">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th scope="col"></th>
                    <th scope="col">id</th>
                    <th scope="col">country</th>
                    <th scope="col">continent</th>
                    <th scope="col">...</th>
                </tr>
            </thead>
            <tbody>
                {% for item in data %}
                    <tr>
                        <td>
                            <input type="checkbox" name="list_gap" value="{{ item.id }}">
                        </td>
                        <td>{{ item.id}}</td>
                        <td>{{ item.country }}</td>
                        <td>{{ item.continent}}</td>
                        <td>...</td>

视图.py

if request.method == 'POST':
    checked_data = request.POST.getlist('list_gap')

但如前所述,这只会让我得到一个已检查 ID 的列表!有没有办法将行的所有数据放入多维列表中,例如..?

list_checked = [
    [1, 'country', 'continent', '...'],
    [2, 'country', 'continent', '...'],
    [3, 'country', 'continent', '...'],
    ...
]

感谢您的所有帮助和晚安!

标签: pythonhtmldjangohtml-tablesubmit

解决方案


我建议创建一个查询集以从数据库中提取实例。

checked_data = request.POST.getlist('list_gap')
checked_instances = Model.objects.filter(id__in=checked_data)

推荐阅读