【问题标题】:Search query with checkbox modifiers in Django在 Django 中使用复选框修饰符搜索查询
【发布时间】: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


    【解决方案1】:

    如果有人对我为我的案例找到的解决方案感兴趣,这就是它的工作原理:

    from functools import reduce
    from operator import or_
    
    def index(request):
        if 'q' in request.GET:
            q = str(request.GET['q'])
            filters = request.GET.getlist('filters')
            queryset = []
            for filter in filters:
                filter_concat = '%s__icontains' % filter
                queryset.append(Q(**{filter_concat: q}))
            result = reduce(or_, queryset)
            data = Data.objects.filter(result).order_by('id')
    
        context = {
            'data': data
        }
        
        return render(request, 'app/index.html', context)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      相关资源
      最近更新 更多