简体   繁体   English

django Model 按列表过滤

[英]django Model filter by list

i am getting list of value from checked checkbox, Now i want to filter the list with my model and get only filter result of value in list我从选中的复选框中获取值列表,现在我想用我的 model 过滤列表,并只获得列表中值的过滤结果

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>

i am getting the selectedTests a list of values now i want the list of values to filter in models and get all data of the values.我正在为 selectedTests 获取值列表,现在我希望值列表在模型中过滤并获取值的所有数据。

You can try to split the values by a comma:您可以尝试用逗号分隔值:

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)

You will need to return some HTTP result for (1) (when the format is not respected), and (2) when the request does not contain a selectedTests value in the first place.您将需要返回一些 HTTP 结果(1)(当不遵守格式时),以及(2)当请求首先不包含selectedTests值时。

That being said, it might be better to just define the checkboxes as:话虽如此,最好将复选框定义为:

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

such that you do not have to rely on JavaScript to inject the selected values in the hidden input element.这样您就不必依赖 JavaScript 在隐藏的输入元素中注入选定的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM