使用* args和** kwargs在Django中进行动态查询

时间:2015-07-13 20:21:06

标签: python django django-forms django-views django-queryset

我正在尝试创建一个搜索表单,用户可以从中选择一些选项来过滤搜索。我收到了这个错误:

  *之后的

sortedByScore()参数必须是序列,而不是Q

views.py:

def results(request):
    if request.method != "GET":
        return HttpResponse("request method needs to be GET")
    else:
        bound_search_form = SearchForm(request.GET)
        query = request.GET['query']
        subject = request.GET['subject']
        grade = request.GET['grade']
        order_by = request.GET['order_by']
        kwargs = {}
        args = ()
        if query:
            query_word_list = query.split()
            args = reduce(operator.or_, ((Q(title__contains=x) | Q(content__contains=x)) for x in query_word_list))
        if subject != 'all':
            kwargs["subject"] = subject

        summaries_list = Summary.objects.sortedByScore(*args, **kwargs)
        length = len(summaries_list)

        # pagination
        paginator = Paginator(summaries_list, 4)

        # get page number from GET request
        page_num = request.GET.get('page', 1)

        # get summaries from paginator according to page number
        try:
            summaries = paginator.page(page_num)
        except(EmptyPage, InvalidPage):
            summaries = paginator.page(paginator.num_pages)

        context_dict = {
            'sumAmount': length,
            'summaries': summaries,
            'search_form': bound_search_form,
        }

        return render(request, 'results.html', context_dict)
我的自定义管理器sortedByScore的

代码:

class SummaryManager(models.Manager):
    def sortedByScore(self, *args, **kwargs):
        summaries = self.get_queryset().filter(*args, **kwargs)
        return sorted(summaries, key=lambda summary: summary.get_score(),reverse=True)

2 个答案:

答案 0 :(得分:2)

args = reduce(operator.or_, ((Q(title__contains=x) | Q(content__contains=x)) for x in query_word_list))

reduce将迭代减少到单个对象,因此在此行args之后不是可迭代的。这会将args降低为单个Q对象,OR query_word_list中的所有项目。如果你想使用*语法传递它,你需要将它包装在一个可迭代的中,即args = (args,)

答案 1 :(得分:0)

sortedByScore(*args, **kwargs)的第一个参数是Q对象:

args = reduce(operator.or_, ((Q(title__contains=x) | Q(content__contains=x)) for x in query_word_list))

您需要重新定义方法以传入不同的参数和/或在方法中执行reduce