【问题标题】:django Model filter by listdjango模型按列表过滤
【发布时间】:2020-08-02 03:42:42
【问题描述】:

我正在从选中的复选框中获取值列表,现在我想用我的模型过滤列表并仅获取列表中值的过滤结果

views.py
def ResultTest(request):
    var = request.POST.get('selectedTests')
    var1 = BookTest.objects.filter(test=v)
   return render(request, 'posts/result.html',{'var1':var1})
html file
    <div class="col-md-12" style="overflow: auto;">
        <input type="hidden" id="selectedTests" name="selectedTests">
        <input type="hidden" name="test_type" value="pathology">
        <table id="example" class="display" >
            <thead>
                <tr>
                    <th>Sr.No</th>
                    <th>Select</th>
                    <th>Test</th>
                    <th>MRP</th>
                    <th>CC Rate</th>


                </tr>
            </thead>
            <tbody>

                {% for booktest in contact_list %}
                <tr>
                    <td>{{ booktest.number }}
                    <td><input type="checkbox" name="check_list[]" value="{{ booktest.test }}" class="chkbox"/> </td>             
                    <td>{{ booktest.test }}</td>
                    <td>{{ booktest.mrp }} </td>
                    <td>{{ booktest.rate }}</td>



                </tr>


               {% endfor %}
            </tbody>

        </table>

我正在为 selectedTests 获取值列表,现在我希望值列表在模型中过滤并获取值的所有数据。

【问题讨论】:

  • selectedTests 中究竟存储了什么值(什么格式)?我不确定在这里使用隐藏字段是否是个好主意,因为它很容易被操纵。
  • 实际上它的复选框选中值存储在 selectedTests 中,因此用户选中多个复选框,因此我在 selectedTests 中获得选中复选框的值列表,现在我想根据存储在中的值列表对其进行过滤selectedTests
  • 好的,的格式是什么?是"1,2,3,4",还是"1 2 3 4",还是别的什么?为什么不直接发送复选框的值?
  • 值在“1,2,3,4”中

标签: javascript python django django-models filter


【解决方案1】:

您可以尝试用逗号分隔值:

def result_test(request):
    selected = request.POST.get('selectedTests')
    if selected is not None:
        try:
            booktests = BookTest.objects.filter(test__in=selected.split(','))
        except ValueError:
            # … (1)
        else:
            return render(request, 'posts/result.html',{'var1':booktest})
    else:
        # … (2)

您需要为 (1)(不遵守格式)和 (2) 当请求首先不包含 selectedTests 值时返回一些 HTTP 结果。

话虽如此,最好将复选框定义为:

<input type="checkbox" name="selectedTests[]" /> option 1
<input type="checkbox" name="selectedTests[]" /> option 2

这样您就不必依赖 JavaScript 在隐藏的输入元素中注入所选值。

【讨论】:

  • 对不起,因为我是 django 的新手,这听起来很愚蠢,如何在我的 django 模板中使用 { 'var1':booktest }。这样我就可以获得所有相关的值
  • @SumeetSingh:在您渲染的模板中 var1 是一组 BookTest 对象,因此您可以例如迭代这些对象,并编写 {% for booktest in var1 %} ... {% endfor %} 并在两者之间渲染 booktests {% for ... %}{% endfor %}。例如:docs.djangoproject.com/en/dev/ref/templates/builtins/#for
  • 我在上面尝试了以下操作,但我只得到列表中第一个值的结果,例如,如果列表是 [1,2,3,4],我在我的Django 模板
  • 非常感谢@WillemVanOnsem,它只是对模型进行了一些小的改动,然后就成功了
  • 有什么方法可以将这些列表存储在 django 数据库中,它显示错误 multivalue dict 错误。
猜你喜欢
  • 2014-08-22
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 2018-02-22
  • 1970-01-01
  • 2014-09-19
  • 1970-01-01
相关资源
最近更新 更多