动态组合Q() - OR对象

时间:2018-03-09 15:28:23

标签: django django-queryset django-q

我正在尝试在此ListView中创建动态搜索。我的想法是每次尝试继承此视图时指定字段和搜索类型。

我的问题是每次我尝试进行搜索时,它只适用于元组的第一个字段。在我的示例中:requests__email是第一个字段,当我在查询“app”后打印对象query_q时,我得到以下输出:

(OR: (AND: ), ('requests__email__icontains', 'app'), (AND: ('requests__email__icontains', 'app'), ('status__icontains', 'app')), (AND: ('requests__email__icontains', 'app'), ('status__icontains', 'app'), ('license_type__name__icontains', 'app')))

我不明白为什么,因为我正在使用运算符,我认为它在|=中可以正常运行query_q |= Q(**query_kwargs)。如果我尝试根据其他属性进行搜索,例如status,则搜索无效。

views.py

class DefaultListView(ListView):
    searchable_fields = (
        ('requests__email', 'icontains'),
        ('status', 'icontains'),
        ('license_type__name', 'icontains'),
    )

    def get_queryset(self):
        form = self.form_class(self.request.GET)

        if form.is_valid():
            if not self.searchable_fields:
                raise AttributeError('searchable_fields has not been configured.')
            term = form.cleaned_data['term']
            query_kwargs = dict()
            query_q = Q()

            # Build a list of Q objects based on the searchable attribute
            for field, search_type in self.searchable_fields:
                query_kwargs["{0}__{1}".format(field, search_type)] = term
                query_q |= Q(**query_kwargs)

            ordering = self.get_ordering()
            queryset = self.model.objects.filter(query_q)

            if ordering:
                return queryset.order_by(**ordering)

            return queryset
        return super(DefaultListView, self).get_queryset()

1 个答案:

答案 0 :(得分:1)

如果您想要将查询构建为X = Y或W = Z,那是因为

query_kwargs["{0}__{1}".format(field, search_type)] = term

您在循环的每次迭代中向query_kwargs添加更多键,而不是重新创建变量 会建议这样的事情

for field, search_type in self.searchable_fields:
    query_q |= Q(**{"{0}__{1}".format(field, search_type): term})