Django 查询作为复选框形式的字符串数组

Django query as string array from checkboxes form

我想从一个复选框中获取多个输入,然后从我的数据库中过滤掉它。那将类似于:

http://127.0.0.1:8000/data/?class_type=[class_C,class_M]

但是我从查询中收到的是:

http://127.0.0.1:8000/data/?class_type=class_C&class_type=class_M

这是它的编码方式,在 .html:

Data class <br> 
<div class="form-check">
    <input class="form-check-input" type="checkbox" value="class_C" id="class_C" name="class_type">
    <label class="form-check-label" for="class_C">
        C
    </label>
</div>

<div class="form-check">
    <input class="form-check-input" type="checkbox" value="class_M" id="class_M" name="class_type">
    <label class="form-check-label" for="class_M">
        M
    </label>
</div>

<div class="form-check">
    <input class="form-check-input" type="checkbox" value="class_X" id="class_X" name="class_type">
    <label class="form-check-label" for="class_X">
        X
    </label>
</div> 

views.py:

data_class = request.GET.get('class_type')

 [...]

if data_class == "class_C":
    database = database.filter(class_l__contains = "C")
elif data_class == "class_M":
    database = database.filter(class_l__contains = "M")
elif data_class == "class_X":
    database = database.filter(class_l__contains = "X")

非常感谢任何帮助!谢谢!

您可以通过.getlist(…) [Django-doc]获取列表:

from django.db.models import <strong>Q</strong>

data_classes = request.GET<strong>.getlist(</strong>'class_type'<strong>)</strong>

acceptable_values = {'class_C', 'class_M', 'class_X'}

if all(data_class in acceptable_values for data_class in data_classes):
    query = Q(*[Q(('class_l_contains', value)) for value in data_classes])
    database = database.filter(query)

或逻辑或:

from django.db.models import Q

data_classes = request.GET.getlist('class_type')

acceptable_values = {'class_C', 'class_M', 'class_X'}

if all(data_class in acceptable_values for data_class in data_classes):
    query = Q(
        *[Q(('class_l_contains', value)) for value in data_classes],
        <strong>_connector=Q.OR</strong>
    )
    database = database.filter(query)