【发布时间】:2022-12-16 07:43:52
【问题描述】:
我正在尝试根据选定的复选框在 Django 中创建动态搜索,如下图所示:
我已经阅读了有关查询的官方文档,但在考虑修饰符的情况下创建查询时遇到了困难。
如果我对过滤器进行硬编码,搜索就可以进行,但是这个想法是用户能够进行多个条件搜索。
我从列表中的表单中获取选定的复选框,并将搜索值作为“q”变量。 然后我无法弄清楚如何使过滤条件动态化以获取所需的查询集并将其返回到搜索结果页面
def index(request):
if 'q' in request.GET:
q = request.GET['q']
filters = request.GET.getlist('filters')
# Here I want to iterate trough the filters list list and set it dynamically
# in the below query as filter based on the selected checkboxes listed
# in the filters list received from the form.
multiple_q = (Q(subject_name__icontains=q) | Q(business_service__icontains=q) |
Q(assignment_group__icontains=q) | Q(comment__icontains=q))
data = Data.objects.filter(multiple_q)
context = {
'data': data
}
return render(request, 'app/index.html', context)
我尝试将 Q 查询构造为字符串,但它没有按预期执行查询。
预先感谢您的建议!
【问题讨论】:
标签: python-3.x django-models django-forms